--- /dev/null
+[patterns]
+
+**.txt = native
+
+**.java = native
+**.properties = LF
+
+**.xml = LF
+**.xsd = LF
+
+**.css = LF
+**.html = LF
+**.png = BIN
-[UTF-8 Japanese]\r
-\r
-\r
-JinParser 変更履歴\r
-\r
-\r
-1.407.4 (2011-05-10)\r
- ・リファクタリングのみ、仕様変更無し。\r
- ・Mavenプラグイン更新。\r
-\r
-1.407.2 (2010-12-02)\r
- ・G国メッセージ追加に伴い JinCore 1.206.2 版に対応。\r
-\r
-1.406.2 (2010-11-29)\r
- ・G国メッセージ追加に伴い JinCore 1.205.2 版に対応。\r
-\r
-1.405.2 (2010-08-26)\r
- ・G国定員増(Max16名)に伴い JinCore 1.204.2 版に対応。\r
-\r
-1.404.4 (2010-08-26)\r
- ・MavenとMercurialによる開発体制に移行。\r
-\r
-1.404.2 (2010-05-13)\r
- ・EXECUTEDメッセージで処刑対象が現れない場合に対処。(バグ報告#21688)\r
-\r
-1.403.2 (2010-03-25)\r
- ・reloadインジケータより後のシステムイベントに対応。\r
- ・ASKENTRYメッセージの変更に対処。\r
-\r
-1.402.2 (2010-03-16)\r
- ・">>00"のようなありえないG国アンカー表記を無視する。\r
-\r
-1.401.2 (2010-03-15)\r
- ・G国のUTF-8化に対応。\r
- ・G国の新システムイベントに対応。\r
-\r
-1.359.2 (2010-01-17)\r
- ・進行中1日目のASKCOMMITメッセージのパースエラーに対処。(改善要求#20321)\r
-\r
-1.358.2 (2009-10-22)\r
- ・JinCore 1.110.2 版に対処。\r
-\r
-1.357.2 (2009-09-10)\r
- ・JinCore 1.109.2 版に対処。\r
-\r
-1.105.2 (2009-09-09)\r
- ・文字実体参照解決処理の改善により文字列コピー量を軽減。\r
- ・文字列記憶容量の事前確保処理により文字列コピー量を軽減。\r
-\r
-1.104.2 (2009-08-29)\r
- ・ビルド環境の整備。\r
- ・ユニットテストの整備。\r
- ・各種ソースコード診断に対処。\r
- ・Javadocコメントの大幅な改善。\r
- ・Shift_JISデコードエラーの揺らぎを吸収。\r
- ・文字列処理の高速化。\r
-\r
-1.103.2 (2009-08-09)\r
- ・JinCore 1.106.2 版に対処。\r
-\r
-1.102.2 (2009-08-08)\r
- ・JinCore 1.105.4 版に対処。\r
- ・カスタムビルドファイルを用意。\r
-\r
-1.101.2 (2009-08-04)\r
- ・初回リリース。\r
-\r
---- EOF ---\r
+[UTF-8 Japanese]
+
+
+JinParser 変更履歴
+
+
+1.407.4 (2011-05-10)
+ ・リファクタリングのみ、仕様変更無し。
+ ・Mavenプラグイン更新。
+
+1.407.2 (2010-12-02)
+ ・G国メッセージ追加に伴い JinCore 1.206.2 版に対応。
+
+1.406.2 (2010-11-29)
+ ・G国メッセージ追加に伴い JinCore 1.205.2 版に対応。
+
+1.405.2 (2010-08-26)
+ ・G国定員増(Max16名)に伴い JinCore 1.204.2 版に対応。
+
+1.404.4 (2010-08-26)
+ ・MavenとMercurialによる開発体制に移行。
+
+1.404.2 (2010-05-13)
+ ・EXECUTEDメッセージで処刑対象が現れない場合に対処。(バグ報告#21688)
+
+1.403.2 (2010-03-25)
+ ・reloadインジケータより後のシステムイベントに対応。
+ ・ASKENTRYメッセージの変更に対処。
+
+1.402.2 (2010-03-16)
+ ・">>00"のようなありえないG国アンカー表記を無視する。
+
+1.401.2 (2010-03-15)
+ ・G国のUTF-8化に対応。
+ ・G国の新システムイベントに対応。
+
+1.359.2 (2010-01-17)
+ ・進行中1日目のASKCOMMITメッセージのパースエラーに対処。(改善要求#20321)
+
+1.358.2 (2009-10-22)
+ ・JinCore 1.110.2 版に対処。
+
+1.357.2 (2009-09-10)
+ ・JinCore 1.109.2 版に対処。
+
+1.105.2 (2009-09-09)
+ ・文字実体参照解決処理の改善により文字列コピー量を軽減。
+ ・文字列記憶容量の事前確保処理により文字列コピー量を軽減。
+
+1.104.2 (2009-08-29)
+ ・ビルド環境の整備。
+ ・ユニットテストの整備。
+ ・各種ソースコード診断に対処。
+ ・Javadocコメントの大幅な改善。
+ ・Shift_JISデコードエラーの揺らぎを吸収。
+ ・文字列処理の高速化。
+
+1.103.2 (2009-08-09)
+ ・JinCore 1.106.2 版に対処。
+
+1.102.2 (2009-08-08)
+ ・JinCore 1.105.4 版に対処。
+ ・カスタムビルドファイルを用意。
+
+1.101.2 (2009-08-04)
+ ・初回リリース。
+
+--- EOF ---
-[UTF-8 Japanese]\r
-\r
-The MIT License\r
-\r
-\r
-Copyright(c) 2009 olyutorskii\r
-\r
-\r
-Permission is hereby granted, free of charge, to any person obtaining a copy\r
-of this software and associated documentation files (the "Software"), to deal\r
-in the Software without restriction, including without limitation the rights\r
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r
-copies of the Software, and to permit persons to whom the Software is\r
-furnished to do so, subject to the following conditions:\r
-\r
-The above copyright notice and this permission notice shall be included in\r
-all copies or substantial portions of the Software.\r
-\r
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r
-THE SOFTWARE.\r
-\r
-\r
-JinParser作者自身からのコメント:\r
-\r
- ※ 少なくともこのソフトウェアの実行、複製、配布、改造は自由です。\r
- ※ 少なくともこのソフトウェアは無保証です。\r
-\r
---- EOF ---\r
+[UTF-8 Japanese]
+
+The MIT License
+
+
+Copyright(c) 2009 olyutorskii
+
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
+
+JinParser作者自身からのコメント:
+
+ ※ 少なくともこのソフトウェアの実行、複製、配布、改造は自由です。
+ ※ 少なくともこのソフトウェアは無保証です。
+
+--- EOF ---
-[UTF-8 Japanese]\r
-\r
- JinParserライブラリ\r
- README\r
-\r
- Copyright(c) 2009 olyutorskii\r
-\r
-\r
-=== JinParserとは ===\r
-\r
- JinParserライブラリは、CGIゲーム「人狼BBS」のクライアント制作者向けに作られた\r
-Javaライブラリです。\r
- このアーカイブは、JinParserライブラリの開発資産を、ある時点で凍結したものです。\r
-\r
- Jindolfは、CGIゲーム「人狼BBS」の専用クライアント開発プロジェクトです。\r
- JinParserは、Jindolf以外の人狼BBSクライアント製作者向けに、\r
-JindolfのXHTML文書パース機能を提供することを目的に発足した、\r
-派生プロジェクトです。\r
-\r
-※ このアーカイブにはJindolfの実行バイナリは含まれていません。\r
- Jindolfを動かしたい方は、jindolfで始まり拡張子が*.jarであるファイルを\r
- 別途入手してください。\r
-※ 人狼BBSのURLは [ http://homepage2.nifty.com/ninjinia/ ] まで\r
-※ 人狼BBSを主催するninjin氏は、JinParserの製作に一切関与していません。\r
- JinParserに関する問い合わせををninjin氏へ投げかけないように!約束だよ!\r
-\r
-\r
-=== ソースコードに関して ===\r
-\r
- - JinParserはJava言語(JLS3)で記述されたプログラムです。\r
- - JinParserは他のプログラムに組み込まれて利用されるライブラリです。\r
- JARファイルによるライブラリ提供や、他プロジェクトのソースツリーへの\r
- マージの形で利用される事を想定しています。\r
- - JinParserはJRE1.5に準拠したJava実行環境で利用できるように作られています。\r
- 原則として、JRE1.5に準拠した実行系であれば、プラットフォームを選びません。\r
-\r
-\r
-=== 依存ライブラリ ===\r
-\r
- - JinParserはビルドに際してJinCoreライブラリを必要とします。\r
- 開発時はMaven等を用いてJinCoreライブラリを用意してください。\r
-\r
-\r
-=== アーカイブ管理体制 ===\r
-\r
- このアーカイブは、UTF-8による開発環境を前提として構成されています。\r
- このアーカイブの原本となる開発資産は、\r
- http://hg.sourceforge.jp/view/jindolf/JinParser/\r
- を上位に持つMercurialリポジトリで管理されています。\r
-\r
-\r
-=== 開発プロジェクト運営元 ===\r
-\r
- http://sourceforge.jp/projects/jindolf/devel/ まで。\r
-\r
-\r
-=== ディレクトリ内訳構成 ===\r
-\r
-基本的にはMaven2のmaven-archetype-quickstart構成に準じます。\r
-\r
-./README.txt\r
- あなたが今見てるこれ。\r
-\r
-./CHANGELOG.txt\r
- 変更履歴。\r
-\r
-./LICENSE.txt\r
- ライセンスに関して。\r
-\r
-./pom.xml\r
- Maven2用プロジェクト構成定義ファイル。\r
-\r
-./build.xml\r
- Ant用追加タスク。\r
-\r
-./src/main/java/\r
- Javaのソースコード。\r
-\r
-./src/main/resources/\r
- プロパティファイルなどの各種リソース。\r
-\r
-./src/test/java/\r
- JUnit 4.* 用のユニットテストコード。\r
-\r
-./src/test/java/sample/\r
- サンプルのパーサ実装。\r
-\r
-./src/main/config/checks.xml\r
- Checkstyle用configファイル。\r
-\r
-./src/main/config/pmdrules.xml\r
- PMD用ルール定義ファイル。\r
-\r
-./src/main/assembly/descriptor.xml\r
- ソースアーカイブ構成定義ファイル。\r
-\r
-\r
---- EOF ---\r
+[UTF-8 Japanese]
+
+ JinParserライブラリ
+ README
+
+ Copyright(c) 2009 olyutorskii
+
+
+=== JinParserとは ===
+
+ JinParserライブラリは、CGIゲーム「人狼BBS」のクライアント制作者向けに作られた
+Javaライブラリです。
+ このアーカイブは、JinParserライブラリの開発資産を、ある時点で凍結したものです。
+
+ Jindolfは、CGIゲーム「人狼BBS」の専用クライアント開発プロジェクトです。
+ JinParserは、Jindolf以外の人狼BBSクライアント製作者向けに、
+JindolfのXHTML文書パース機能を提供することを目的に発足した、
+派生プロジェクトです。
+
+※ このアーカイブにはJindolfの実行バイナリは含まれていません。
+ Jindolfを動かしたい方は、jindolfで始まり拡張子が*.jarであるファイルを
+ 別途入手してください。
+※ 人狼BBSのURLは [ http://homepage2.nifty.com/ninjinia/ ] まで
+※ 人狼BBSを主催するninjin氏は、JinParserの製作に一切関与していません。
+ JinParserに関する問い合わせををninjin氏へ投げかけないように!約束だよ!
+
+
+=== ソースコードに関して ===
+
+ - JinParserはJava言語(JLS3)で記述されたプログラムです。
+ - JinParserは他のプログラムに組み込まれて利用されるライブラリです。
+ JARファイルによるライブラリ提供や、他プロジェクトのソースツリーへの
+ マージの形で利用される事を想定しています。
+ - JinParserはJRE1.5に準拠したJava実行環境で利用できるように作られています。
+ 原則として、JRE1.5に準拠した実行系であれば、プラットフォームを選びません。
+
+
+=== 依存ライブラリ ===
+
+ - JinParserはビルドに際してJinCoreライブラリを必要とします。
+ 開発時はMaven等を用いてJinCoreライブラリを用意してください。
+
+
+=== アーカイブ管理体制 ===
+
+ このアーカイブは、UTF-8による開発環境を前提として構成されています。
+ このアーカイブの原本となる開発資産は、
+ http://hg.sourceforge.jp/view/jindolf/JinParser/
+ を上位に持つMercurialリポジトリで管理されています。
+
+
+=== 開発プロジェクト運営元 ===
+
+ http://sourceforge.jp/projects/jindolf/devel/ まで。
+
+
+=== ディレクトリ内訳構成 ===
+
+基本的にはMaven2のmaven-archetype-quickstart構成に準じます。
+
+./README.txt
+ あなたが今見てるこれ。
+
+./CHANGELOG.txt
+ 変更履歴。
+
+./LICENSE.txt
+ ライセンスに関して。
+
+./pom.xml
+ Maven2用プロジェクト構成定義ファイル。
+
+./build.xml
+ Ant用追加タスク。
+
+./src/main/java/
+ Javaのソースコード。
+
+./src/main/resources/
+ プロパティファイルなどの各種リソース。
+
+./src/test/java/
+ JUnit 4.* 用のユニットテストコード。
+
+./src/test/java/sample/
+ サンプルのパーサ実装。
+
+./src/main/config/checks.xml
+ Checkstyle用configファイル。
+
+./src/main/config/pmdrules.xml
+ PMD用ルール定義ファイル。
+
+./src/main/assembly/descriptor.xml
+ ソースアーカイブ構成定義ファイル。
+
+
+--- EOF ---
-/*\r
- * abstract XHTML parser\r
- *\r
- * License : The MIT License\r
- * Copyright(c) 2009 olyutorskii\r
- */\r
-\r
-package jp.sourceforge.jindolf.parser;\r
-\r
-import java.util.regex.Matcher;\r
-import java.util.regex.Pattern;\r
-import jp.sourceforge.jindolf.corelib.GameRole;\r
-\r
-/**\r
- * 人狼BBS生成のXHTML文書を解釈するパーサの抽象基底クラス。\r
- * {@link DecodedContent}の内容をパースし、\r
- * 各種ハンドラへ通知する処理の基盤を構成する。\r
- * 正規表現エンジンを実装基盤とする。\r
- * 親パーサを指定することにより、検索対象文字列とマッチエンジンを\r
- * 親パーサと共有することができる。\r
- * @see Matcher\r
- */\r
-public abstract class AbstractParser implements ChainedParser{\r
-\r
- /** ホワイトスペース。 */\r
- protected static final String SPCHAR = "\u0020\\t\\n\\r";\r
- /** 0回以上連続するホワイトスペースの正規表現。 */\r
- protected static final String SP_I = "[" +SPCHAR+ "]*";\r
-\r
- private static final Pattern DUMMY_PATTERN = compile("\u0000");\r
-\r
-\r
- private final ChainedParser parent;\r
-\r
- private DecodedContent content;\r
- private Matcher matcher;\r
- private String contextErrorMessage;\r
-\r
-\r
- /**\r
- * コンストラクタ。\r
- */\r
- protected AbstractParser(){\r
- this(null);\r
- return;\r
- }\r
-\r
- /**\r
- * コンストラクタ。\r
- * @param parent 親パーサ\r
- */\r
- protected AbstractParser(ChainedParser parent){\r
- super();\r
- this.parent = parent;\r
- resetImpl();\r
- return;\r
- }\r
-\r
-\r
- /**\r
- * 正規表現のコンパイルを行う。\r
- * デフォルトで{@link java.util.regex.Pattern#DOTALL}が\r
- * オプション指定される。\r
- * @param regex 正規表現文字列\r
- * @return マッチエンジン\r
- */\r
- protected static Pattern compile(CharSequence regex){\r
- Pattern result = Pattern.compile(regex.toString(), Pattern.DOTALL);\r
- return result;\r
- }\r
-\r
- /**\r
- * パーサの状態をコンストラクタ直後の状態にリセットする。\r
- * ※コンストラクタから呼ばせるためにオーバーライド不可\r
- */\r
- private void resetImpl(){\r
- this.content = null;\r
- this.matcher = null;\r
- this.contextErrorMessage = null;\r
- return;\r
- }\r
-\r
- /**\r
- * パーサの状態をリセットする。\r
- */\r
- public void reset(){\r
- if(this.parent != null){\r
- throw new UnsupportedOperationException();\r
- }\r
- resetImpl();\r
- return;\r
- }\r
-\r
- /**\r
- * パース対象文字列をセットする。\r
- * パースが終わるまでこの文字列の内容を変更してはならない。\r
- * @param content パース対象文字列\r
- */\r
- public void setContent(DecodedContent content){\r
- if(this.parent != null){\r
- throw new UnsupportedOperationException();\r
- }\r
-\r
- CharSequence rawContent = content.getRawContent();\r
-\r
- this.content = content;\r
- this.matcher = DUMMY_PATTERN.matcher(rawContent);\r
-\r
- return;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @return {@inheritDoc}\r
- */\r
- @Override\r
- public DecodedContent getContent(){\r
- if(this.parent != null){\r
- return this.parent.getContent();\r
- }\r
-\r
- return this.content;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @return {@inheritDoc}\r
- */\r
- @Override\r
- public Matcher getMatcher(){\r
- if(this.parent != null){\r
- return this.parent.getMatcher();\r
- }\r
-\r
- return this.matcher;\r
- }\r
-\r
- /**\r
- * 文脈依存のエラーメッセージを設定する。\r
- * {@link #buildParseException}で利用される。\r
- * 設定内容は親へ委譲されない。\r
- * @param errorMessage エラーメッセージ。nullも可能。\r
- */\r
- protected void setContextErrorMessage(String errorMessage){\r
- this.contextErrorMessage = errorMessage;\r
- return;\r
- }\r
-\r
- /**\r
- * 文脈状況に応じたパース例外を生成する。\r
- * 例外にはリージョン開始位置が埋め込まれる。\r
- * @return パース例外\r
- */\r
- protected HtmlParseException buildParseException(){\r
- HtmlParseException result;\r
- result = new HtmlParseException(this.contextErrorMessage,\r
- regionStart() );\r
- return result;\r
- }\r
-\r
- /**\r
- * パースに使う正規表現パターンを切り替える。\r
- * @param pattern 正規表現パターン\r
- */\r
- protected void switchPattern(Pattern pattern){\r
- getMatcher().usePattern(pattern);\r
- return;\r
- }\r
-\r
- /**\r
- * 最後のマッチに成功した文字領域以前をパース対象から外す。\r
- */\r
- protected void shrinkRegion(){\r
- int lastMatchedEnd;\r
- try{\r
- lastMatchedEnd = matchEnd();\r
- }catch(IllegalStateException e){\r
- return;\r
- }\r
-\r
- int regionEnd = regionEnd();\r
-\r
- getMatcher().region(lastMatchedEnd, regionEnd);\r
-\r
- return;\r
- }\r
-\r
- /**\r
- * 検査対象の一部が指定パターンにマッチするか判定する。\r
- * @param pattern 指定パターン\r
- * @return マッチすればtrue\r
- */\r
- protected boolean findProbe(Pattern pattern){\r
- switchPattern(pattern);\r
- if( getMatcher().find() ) return true;\r
- return false;\r
- }\r
-\r
- /**\r
- * 検査対象先頭が指定パターンにマッチするか判定する。\r
- * @param pattern 指定パターン\r
- * @return マッチすればtrue\r
- */\r
- protected boolean lookingAtProbe(Pattern pattern){\r
- switchPattern(pattern);\r
- if( getMatcher().lookingAt() ) return true;\r
- return false;\r
- }\r
-\r
- /**\r
- * 検査対象全体が指定パターンにマッチするか判定する。\r
- * @param pattern 指定パターン\r
- * @return マッチすればtrue\r
- */\r
- protected boolean matchesProbe(Pattern pattern){\r
- switchPattern(pattern);\r
- if( getMatcher().matches() ) return true;\r
- return false;\r
- }\r
-\r
- /**\r
- * 残りの検索対象領域からパターンがマッチする部分を探す。\r
- * 見つからなければ例外をスローする。\r
- * @param pattern 正規表現パターン\r
- * @throws HtmlParseException\r
- * マッチしなかった\r
- */\r
- protected void findAffirm(Pattern pattern)\r
- throws HtmlParseException{\r
- if( ! findProbe(pattern) ){\r
- throw buildParseException();\r
- }\r
- return;\r
- }\r
-\r
- /**\r
- * 残りの検索対象領域先頭からパターンがマッチする部分を探す。\r
- * 見つからなければ例外をスローする。\r
- * @param pattern 正規表現パターン\r
- * @throws HtmlParseException\r
- * マッチしなかった\r
- */\r
- protected void lookingAtAffirm(Pattern pattern)\r
- throws HtmlParseException{\r
- if( ! lookingAtProbe(pattern) ){\r
- throw buildParseException();\r
- }\r
- return;\r
- }\r
-\r
- /**\r
- * 残りの検索対象領域全体がパターンにマッチするか調べる。\r
- * マッチしなければ例外をスローする。\r
- * @param pattern 正規表現パターン\r
- * @throws HtmlParseException\r
- * マッチしなかった\r
- */\r
- protected void matchesAffirm(Pattern pattern)\r
- throws HtmlParseException{\r
- if( ! matchesProbe(pattern) ){\r
- throw buildParseException();\r
- }\r
- return;\r
- }\r
-\r
- /**\r
- * 最後のマッチで任意の前方参照グループがヒットしたか判定する。\r
- * @param group グループ番号\r
- * @return ヒットしていたらtrue\r
- */\r
- protected boolean isGroupMatched(int group){\r
- if(matchStart(group) >= 0) return true;\r
- return false;\r
- }\r
-\r
- /**\r
- * 最後にマッチした前方参照グループを数値化する。\r
- * 0以上の整数のみサポート。\r
- * @param group グループ番号\r
- * @return 数値\r
- */\r
- protected int parseGroupedInt(int group){\r
- int result = 0;\r
-\r
- CharSequence rawContent = getContent().getRawContent();\r
- int start = matchStart(group);\r
- int end = matchEnd(group);\r
- for(int pos = start; pos < end; pos++){\r
- char letter = rawContent.charAt(pos);\r
- int digit = Character.digit(letter, 10);\r
- result = result * 10 + digit;\r
- }\r
-\r
- return result;\r
- }\r
-\r
- /**\r
- * 最後にマッチした前方参照グループの開始位置を得る。\r
- * @param group 前方参照識別番号\r
- * @return 開始位置\r
- */\r
- protected int matchStart(int group){\r
- return getMatcher().start(group);\r
- }\r
-\r
- /**\r
- * 最後にマッチした前方参照グループの終了位置を得る。\r
- * @param group 前方参照識別番号\r
- * @return 終了位置\r
- */\r
- protected int matchEnd(int group){\r
- return getMatcher().end(group);\r
- }\r
-\r
- /**\r
- * 最後にマッチした全領域の開始位置を得る。\r
- * @return 開始位置\r
- */\r
- protected int matchStart(){\r
- return getMatcher().start();\r
- }\r
-\r
- /**\r
- * 最後にマッチした全領域の終了位置を得る。\r
- * @return 終了位置\r
- */\r
- protected int matchEnd(){\r
- return getMatcher().end();\r
- }\r
-\r
- /**\r
- * 検索領域の先頭位置を返す。\r
- * @return 先頭位置\r
- */\r
- protected int regionStart(){\r
- return getMatcher().regionStart();\r
- }\r
-\r
- /**\r
- * 検索領域の末尾位置を返す。\r
- * @return 末尾位置\r
- */\r
- protected int regionEnd(){\r
- return getMatcher().regionEnd();\r
- }\r
-\r
- /**\r
- * 0個以上のホワイトスペースを読み飛ばす。\r
- * 具体的には検索対象領域の先頭が進むだけ。\r
- */\r
- protected void sweepSpace(){\r
- CharSequence rawContent = getContent().getRawContent();\r
-\r
- boolean hasSpace = false;\r
- int regionStart = regionStart();\r
- int regionEnd = regionEnd();\r
-\r
- for( ; regionStart < regionEnd; regionStart++){\r
- char letter = rawContent.charAt(regionStart);\r
-\r
- switch(letter){\r
- case '\u0020':\r
- case '\t':\r
- case '\n':\r
- case '\r':\r
- hasSpace = true;\r
- continue;\r
- default:\r
- break;\r
- }\r
-\r
- break;\r
- }\r
-\r
- if(hasSpace){\r
- getMatcher().region(regionStart, regionEnd);\r
- }\r
-\r
- return;\r
- }\r
-\r
- /**\r
- * 検索領域の先頭から各種役職名のマッチを試みる。\r
- * @return 役職。何もマッチしなければnullを返す。\r
- */\r
- protected GameRole lookingAtRole(){\r
- GameRole role = GameRole.lookingAtRole(getMatcher());\r
- return role;\r
- }\r
-\r
-}\r
+/*
+ * abstract XHTML parser
+ *
+ * License : The MIT License
+ * Copyright(c) 2009 olyutorskii
+ */
+
+package jp.sourceforge.jindolf.parser;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import jp.sourceforge.jindolf.corelib.GameRole;
+
+/**
+ * 人狼BBS生成のXHTML文書を解釈するパーサの抽象基底クラス。
+ * {@link DecodedContent}の内容をパースし、
+ * 各種ハンドラへ通知する処理の基盤を構成する。
+ * 正規表現エンジンを実装基盤とする。
+ * 親パーサを指定することにより、検索対象文字列とマッチエンジンを
+ * 親パーサと共有することができる。
+ * @see Matcher
+ */
+public abstract class AbstractParser implements ChainedParser{
+
+ /** ホワイトスペース。 */
+ protected static final String SPCHAR = "\u0020\\t\\n\\r";
+ /** 0回以上連続するホワイトスペースの正規表現。 */
+ protected static final String SP_I = "[" +SPCHAR+ "]*";
+
+ private static final Pattern DUMMY_PATTERN = compile("\u0000");
+
+
+ private final ChainedParser parent;
+
+ private DecodedContent content;
+ private Matcher matcher;
+ private String contextErrorMessage;
+
+
+ /**
+ * コンストラクタ。
+ */
+ protected AbstractParser(){
+ this(null);
+ return;
+ }
+
+ /**
+ * コンストラクタ。
+ * @param parent 親パーサ
+ */
+ protected AbstractParser(ChainedParser parent){
+ super();
+ this.parent = parent;
+ resetImpl();
+ return;
+ }
+
+
+ /**
+ * 正規表現のコンパイルを行う。
+ * デフォルトで{@link java.util.regex.Pattern#DOTALL}が
+ * オプション指定される。
+ * @param regex 正規表現文字列
+ * @return マッチエンジン
+ */
+ protected static Pattern compile(CharSequence regex){
+ Pattern result = Pattern.compile(regex.toString(), Pattern.DOTALL);
+ return result;
+ }
+
+ /**
+ * パーサの状態をコンストラクタ直後の状態にリセットする。
+ * ※コンストラクタから呼ばせるためにオーバーライド不可
+ */
+ private void resetImpl(){
+ this.content = null;
+ this.matcher = null;
+ this.contextErrorMessage = null;
+ return;
+ }
+
+ /**
+ * パーサの状態をリセットする。
+ */
+ public void reset(){
+ if(this.parent != null){
+ throw new UnsupportedOperationException();
+ }
+ resetImpl();
+ return;
+ }
+
+ /**
+ * パース対象文字列をセットする。
+ * パースが終わるまでこの文字列の内容を変更してはならない。
+ * @param content パース対象文字列
+ */
+ public void setContent(DecodedContent content){
+ if(this.parent != null){
+ throw new UnsupportedOperationException();
+ }
+
+ CharSequence rawContent = content.getRawContent();
+
+ this.content = content;
+ this.matcher = DUMMY_PATTERN.matcher(rawContent);
+
+ return;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @return {@inheritDoc}
+ */
+ @Override
+ public DecodedContent getContent(){
+ if(this.parent != null){
+ return this.parent.getContent();
+ }
+
+ return this.content;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @return {@inheritDoc}
+ */
+ @Override
+ public Matcher getMatcher(){
+ if(this.parent != null){
+ return this.parent.getMatcher();
+ }
+
+ return this.matcher;
+ }
+
+ /**
+ * 文脈依存のエラーメッセージを設定する。
+ * {@link #buildParseException}で利用される。
+ * 設定内容は親へ委譲されない。
+ * @param errorMessage エラーメッセージ。nullも可能。
+ */
+ protected void setContextErrorMessage(String errorMessage){
+ this.contextErrorMessage = errorMessage;
+ return;
+ }
+
+ /**
+ * 文脈状況に応じたパース例外を生成する。
+ * 例外にはリージョン開始位置が埋め込まれる。
+ * @return パース例外
+ */
+ protected HtmlParseException buildParseException(){
+ HtmlParseException result;
+ result = new HtmlParseException(this.contextErrorMessage,
+ regionStart() );
+ return result;
+ }
+
+ /**
+ * パースに使う正規表現パターンを切り替える。
+ * @param pattern 正規表現パターン
+ */
+ protected void switchPattern(Pattern pattern){
+ getMatcher().usePattern(pattern);
+ return;
+ }
+
+ /**
+ * 最後のマッチに成功した文字領域以前をパース対象から外す。
+ */
+ protected void shrinkRegion(){
+ int lastMatchedEnd;
+ try{
+ lastMatchedEnd = matchEnd();
+ }catch(IllegalStateException e){
+ return;
+ }
+
+ int regionEnd = regionEnd();
+
+ getMatcher().region(lastMatchedEnd, regionEnd);
+
+ return;
+ }
+
+ /**
+ * 検査対象の一部が指定パターンにマッチするか判定する。
+ * @param pattern 指定パターン
+ * @return マッチすればtrue
+ */
+ protected boolean findProbe(Pattern pattern){
+ switchPattern(pattern);
+ if( getMatcher().find() ) return true;
+ return false;
+ }
+
+ /**
+ * 検査対象先頭が指定パターンにマッチするか判定する。
+ * @param pattern 指定パターン
+ * @return マッチすればtrue
+ */
+ protected boolean lookingAtProbe(Pattern pattern){
+ switchPattern(pattern);
+ if( getMatcher().lookingAt() ) return true;
+ return false;
+ }
+
+ /**
+ * 検査対象全体が指定パターンにマッチするか判定する。
+ * @param pattern 指定パターン
+ * @return マッチすればtrue
+ */
+ protected boolean matchesProbe(Pattern pattern){
+ switchPattern(pattern);
+ if( getMatcher().matches() ) return true;
+ return false;
+ }
+
+ /**
+ * 残りの検索対象領域からパターンがマッチする部分を探す。
+ * 見つからなければ例外をスローする。
+ * @param pattern 正規表現パターン
+ * @throws HtmlParseException
+ * マッチしなかった
+ */
+ protected void findAffirm(Pattern pattern)
+ throws HtmlParseException{
+ if( ! findProbe(pattern) ){
+ throw buildParseException();
+ }
+ return;
+ }
+
+ /**
+ * 残りの検索対象領域先頭からパターンがマッチする部分を探す。
+ * 見つからなければ例外をスローする。
+ * @param pattern 正規表現パターン
+ * @throws HtmlParseException
+ * マッチしなかった
+ */
+ protected void lookingAtAffirm(Pattern pattern)
+ throws HtmlParseException{
+ if( ! lookingAtProbe(pattern) ){
+ throw buildParseException();
+ }
+ return;
+ }
+
+ /**
+ * 残りの検索対象領域全体がパターンにマッチするか調べる。
+ * マッチしなければ例外をスローする。
+ * @param pattern 正規表現パターン
+ * @throws HtmlParseException
+ * マッチしなかった
+ */
+ protected void matchesAffirm(Pattern pattern)
+ throws HtmlParseException{
+ if( ! matchesProbe(pattern) ){
+ throw buildParseException();
+ }
+ return;
+ }
+
+ /**
+ * 最後のマッチで任意の前方参照グループがヒットしたか判定する。
+ * @param group グループ番号
+ * @return ヒットしていたらtrue
+ */
+ protected boolean isGroupMatched(int group){
+ if(matchStart(group) >= 0) return true;
+ return false;
+ }
+
+ /**
+ * 最後にマッチした前方参照グループを数値化する。
+ * 0以上の整数のみサポート。
+ * @param group グループ番号
+ * @return 数値
+ */
+ protected int parseGroupedInt(int group){
+ int result = 0;
+
+ CharSequence rawContent = getContent().getRawContent();
+ int start = matchStart(group);
+ int end = matchEnd(group);
+ for(int pos = start; pos < end; pos++){
+ char letter = rawContent.charAt(pos);
+ int digit = Character.digit(letter, 10);
+ result = result * 10 + digit;
+ }
+
+ return result;
+ }
+
+ /**
+ * 最後にマッチした前方参照グループの開始位置を得る。
+ * @param group 前方参照識別番号
+ * @return 開始位置
+ */
+ protected int matchStart(int group){
+ return getMatcher().start(group);
+ }
+
+ /**
+ * 最後にマッチした前方参照グループの終了位置を得る。
+ * @param group 前方参照識別番号
+ * @return 終了位置
+ */
+ protected int matchEnd(int group){
+ return getMatcher().end(group);
+ }
+
+ /**
+ * 最後にマッチした全領域の開始位置を得る。
+ * @return 開始位置
+ */
+ protected int matchStart(){
+ return getMatcher().start();
+ }
+
+ /**
+ * 最後にマッチした全領域の終了位置を得る。
+ * @return 終了位置
+ */
+ protected int matchEnd(){
+ return getMatcher().end();
+ }
+
+ /**
+ * 検索領域の先頭位置を返す。
+ * @return 先頭位置
+ */
+ protected int regionStart(){
+ return getMatcher().regionStart();
+ }
+
+ /**
+ * 検索領域の末尾位置を返す。
+ * @return 末尾位置
+ */
+ protected int regionEnd(){
+ return getMatcher().regionEnd();
+ }
+
+ /**
+ * 0個以上のホワイトスペースを読み飛ばす。
+ * 具体的には検索対象領域の先頭が進むだけ。
+ */
+ protected void sweepSpace(){
+ CharSequence rawContent = getContent().getRawContent();
+
+ boolean hasSpace = false;
+ int regionStart = regionStart();
+ int regionEnd = regionEnd();
+
+ for( ; regionStart < regionEnd; regionStart++){
+ char letter = rawContent.charAt(regionStart);
+
+ switch(letter){
+ case '\u0020':
+ case '\t':
+ case '\n':
+ case '\r':
+ hasSpace = true;
+ continue;
+ default:
+ break;
+ }
+
+ break;
+ }
+
+ if(hasSpace){
+ getMatcher().region(regionStart, regionEnd);
+ }
+
+ return;
+ }
+
+ /**
+ * 検索領域の先頭から各種役職名のマッチを試みる。
+ * @return 役職。何もマッチしなければnullを返す。
+ */
+ protected GameRole lookingAtRole(){
+ GameRole role = GameRole.lookingAtRole(getMatcher());
+ return role;
+ }
+
+}
-/*\r
- * basic handler for XHTML\r
- *\r
- * License : The MIT License\r
- * Copyright(c) 2009 olyutorskii\r
- */\r
-\r
-package jp.sourceforge.jindolf.parser;\r
-\r
-import jp.sourceforge.jindolf.corelib.PeriodType;\r
-import jp.sourceforge.jindolf.corelib.VillageState;\r
-\r
-/**\r
- * 人狼BBSの各種XHTMLの基本的な構造をパースするためのハンドラ。\r
- * このハンドラの全メソッドはパーサ{@link HtmlParser}により呼ばれる。\r
- *\r
- * パーサはパース開始時に{@link #startParse(DecodedContent)}を呼び、\r
- * パース終了直前に{@link #endParse()}を呼ぶ。\r
- * その間に他の様々なメソッドが呼び出される。\r
- *\r
- * 一部のメソッドに渡される{@link DecodedContent}文字列オブジェクトは\r
- * mutableである。\r
- * 後々で内容が必要になるならば、ハンドラはSeqRangeで示されたこの内容の\r
- * 必要な箇所をコピーして保存しなければならない。\r
- *\r
- * フラグメントや属性値中の文字参照記号列の解釈はハンドラ側の責務とする。\r
- *\r
- * 各メソッドは、各々の判断で{@link HtmlParseException}をスローする\r
- * ことにより、パース作業を中断させることができる。\r
- */\r
-public interface BasicHandler{\r
-\r
- /**\r
- * パース開始の通知を受け取る。\r
- * @param content これからパースを始めるXHTML文字列\r
- * @throws HtmlParseException パースエラー\r
- */\r
- void startParse(DecodedContent content) throws HtmlParseException;\r
-\r
- /**\r
- * titleタグの内容の通知を受け取る。\r
- * 例:「人狼BBS:F F2019 新緑の村」。\r
- * @param content パース対象文字列\r
- * @param titleRange タイトルの範囲\r
- * @throws HtmlParseException パースエラー\r
- */\r
- void pageTitle(DecodedContent content, SeqRange titleRange)\r
- throws HtmlParseException;\r
-\r
- /**\r
- * ログイン名(ID)の通知を受け取る。\r
- * ログインせずに得られたページがパース対象であるなら、呼ばれない。\r
- * F国のみで動作確認。\r
- * @param content パース対象文字列\r
- * @param loginRange ログイン名の範囲\r
- * @throws HtmlParseException パースエラー\r
- */\r
- void loginName(DecodedContent content, SeqRange loginRange)\r
- throws HtmlParseException;\r
-\r
- /**\r
- * 読み込んだページ種別を自動認識した結果を伝える。\r
- * ページタイトルもしくはログイン名の通知の後に呼ばれうる。\r
- * @param type ページ種別\r
- * @throws HtmlParseException パースエラー\r
- */\r
- void pageType(PageType type)\r
- throws HtmlParseException;\r
-\r
- /**\r
- * 村の名前の通知を受け取る。\r
- * 国名と番号と愛称に分解するのはハンドラ側の責務。\r
- * 例:「F2019 新緑の村」。\r
- * @param content パース対象文字列\r
- * @param villageRange 村名の範囲\r
- * @throws HtmlParseException パースエラー\r
- */\r
- void villageName(DecodedContent content, SeqRange villageRange)\r
- throws HtmlParseException;\r
-\r
- /**\r
- * 次回更新時刻の通知を受け取る。\r
- * 既に終了した村がパース対象の場合、あまり月日に意味はないかも。\r
- * @param month 更新月\r
- * @param day 更新日\r
- * @param hour 更新時\r
- * @param minute 更新分\r
- * @throws HtmlParseException パースエラー\r
- */\r
- void commitTime(int month, int day, int hour, int minute)\r
- throws HtmlParseException;\r
-\r
- /**\r
- * 他の日へのリンクの通知を受け取る。\r
- * 複数回呼ばれる場合がある。\r
- * @param content パース対象文字列\r
- * @param anchorRange aタグhref属性値の範囲\r
- * @param periodType 日のタイプ。「終了」ならnull。\r
- * @param day 日にち。「プロローグ」、「エピローグ」、「終了」では-1。\r
- * @throws HtmlParseException パースエラー\r
- */\r
- void periodLink(DecodedContent content,\r
- SeqRange anchorRange,\r
- PeriodType periodType, int day)\r
- throws HtmlParseException;\r
-\r
- /**\r
- * 村一覧リスト内の個別の村情報の通知を受け取る。\r
- * @param content パース対象文字列\r
- * @param anchorRange URLの範囲\r
- * @param villageRange 村名の範囲\r
- * @param hour 更新時。不明なら負の数。\r
- * @param minute 更新分。不明なら負の数。\r
- * @param state 村の状態\r
- * @throws HtmlParseException パースエラー\r
- */\r
- void villageRecord(DecodedContent content,\r
- SeqRange anchorRange,\r
- SeqRange villageRange,\r
- int hour, int minute,\r
- VillageState state )\r
- throws HtmlParseException;\r
-\r
- /**\r
- * パースの終了の通知を受け取る。\r
- * @throws HtmlParseException パースエラー\r
- */\r
- void endParse() throws HtmlParseException;\r
-\r
-}\r
+/*
+ * basic handler for XHTML
+ *
+ * License : The MIT License
+ * Copyright(c) 2009 olyutorskii
+ */
+
+package jp.sourceforge.jindolf.parser;
+
+import jp.sourceforge.jindolf.corelib.PeriodType;
+import jp.sourceforge.jindolf.corelib.VillageState;
+
+/**
+ * 人狼BBSの各種XHTMLの基本的な構造をパースするためのハンドラ。
+ * このハンドラの全メソッドはパーサ{@link HtmlParser}により呼ばれる。
+ *
+ * パーサはパース開始時に{@link #startParse(DecodedContent)}を呼び、
+ * パース終了直前に{@link #endParse()}を呼ぶ。
+ * その間に他の様々なメソッドが呼び出される。
+ *
+ * 一部のメソッドに渡される{@link DecodedContent}文字列オブジェクトは
+ * mutableである。
+ * 後々で内容が必要になるならば、ハンドラはSeqRangeで示されたこの内容の
+ * 必要な箇所をコピーして保存しなければならない。
+ *
+ * フラグメントや属性値中の文字参照記号列の解釈はハンドラ側の責務とする。
+ *
+ * 各メソッドは、各々の判断で{@link HtmlParseException}をスローする
+ * ことにより、パース作業を中断させることができる。
+ */
+public interface BasicHandler{
+
+ /**
+ * パース開始の通知を受け取る。
+ * @param content これからパースを始めるXHTML文字列
+ * @throws HtmlParseException パースエラー
+ */
+ void startParse(DecodedContent content) throws HtmlParseException;
+
+ /**
+ * titleタグの内容の通知を受け取る。
+ * 例:「人狼BBS:F F2019 新緑の村」。
+ * @param content パース対象文字列
+ * @param titleRange タイトルの範囲
+ * @throws HtmlParseException パースエラー
+ */
+ void pageTitle(DecodedContent content, SeqRange titleRange)
+ throws HtmlParseException;
+
+ /**
+ * ログイン名(ID)の通知を受け取る。
+ * ログインせずに得られたページがパース対象であるなら、呼ばれない。
+ * F国のみで動作確認。
+ * @param content パース対象文字列
+ * @param loginRange ログイン名の範囲
+ * @throws HtmlParseException パースエラー
+ */
+ void loginName(DecodedContent content, SeqRange loginRange)
+ throws HtmlParseException;
+
+ /**
+ * 読み込んだページ種別を自動認識した結果を伝える。
+ * ページタイトルもしくはログイン名の通知の後に呼ばれうる。
+ * @param type ページ種別
+ * @throws HtmlParseException パースエラー
+ */
+ void pageType(PageType type)
+ throws HtmlParseException;
+
+ /**
+ * 村の名前の通知を受け取る。
+ * 国名と番号と愛称に分解するのはハンドラ側の責務。
+ * 例:「F2019 新緑の村」。
+ * @param content パース対象文字列
+ * @param villageRange 村名の範囲
+ * @throws HtmlParseException パースエラー
+ */
+ void villageName(DecodedContent content, SeqRange villageRange)
+ throws HtmlParseException;
+
+ /**
+ * 次回更新時刻の通知を受け取る。
+ * 既に終了した村がパース対象の場合、あまり月日に意味はないかも。
+ * @param month 更新月
+ * @param day 更新日
+ * @param hour 更新時
+ * @param minute 更新分
+ * @throws HtmlParseException パースエラー
+ */
+ void commitTime(int month, int day, int hour, int minute)
+ throws HtmlParseException;
+
+ /**
+ * 他の日へのリンクの通知を受け取る。
+ * 複数回呼ばれる場合がある。
+ * @param content パース対象文字列
+ * @param anchorRange aタグhref属性値の範囲
+ * @param periodType 日のタイプ。「終了」ならnull。
+ * @param day 日にち。「プロローグ」、「エピローグ」、「終了」では-1。
+ * @throws HtmlParseException パースエラー
+ */
+ void periodLink(DecodedContent content,
+ SeqRange anchorRange,
+ PeriodType periodType, int day)
+ throws HtmlParseException;
+
+ /**
+ * 村一覧リスト内の個別の村情報の通知を受け取る。
+ * @param content パース対象文字列
+ * @param anchorRange URLの範囲
+ * @param villageRange 村名の範囲
+ * @param hour 更新時。不明なら負の数。
+ * @param minute 更新分。不明なら負の数。
+ * @param state 村の状態
+ * @throws HtmlParseException パースエラー
+ */
+ void villageRecord(DecodedContent content,
+ SeqRange anchorRange,
+ SeqRange villageRange,
+ int hour, int minute,
+ VillageState state )
+ throws HtmlParseException;
+
+ /**
+ * パースの終了の通知を受け取る。
+ * @throws HtmlParseException パースエラー
+ */
+ void endParse() throws HtmlParseException;
+
+}
-/*\r
- * chained parser interface\r
- *\r
- * License : The MIT License\r
- * Copyright(c) 2009 olyutorskii\r
- */\r
-\r
-package jp.sourceforge.jindolf.parser;\r
-\r
-import java.util.regex.Matcher;\r
-\r
-/**\r
- * 連結パーサの基本インタフェース。\r
- */\r
-public interface ChainedParser{\r
-\r
- /**\r
- * パース対象文字列を取得する。\r
- * このクラスおよびこのクラスを継承するものは、\r
- * 全てこのメソッドを介してパース対象文字列にアクセスしなければならない。\r
- * @return パース対象文字列\r
- */\r
- DecodedContent getContent();\r
-\r
- /**\r
- * 現時点での正規表現マッチャを得る。\r
- * このクラスおよびこのクラスを継承するものは、\r
- * 全てこのメソッドを介してマッチャにアクセスしなければならない。\r
- * @return 正規表現マッチャ\r
- */\r
- Matcher getMatcher();\r
-\r
-}\r
+/*
+ * chained parser interface
+ *
+ * License : The MIT License
+ * Copyright(c) 2009 olyutorskii
+ */
+
+package jp.sourceforge.jindolf.parser;
+
+import java.util.regex.Matcher;
+
+/**
+ * 連結パーサの基本インタフェース。
+ */
+public interface ChainedParser{
+
+ /**
+ * パース対象文字列を取得する。
+ * このクラスおよびこのクラスを継承するものは、
+ * 全てこのメソッドを介してパース対象文字列にアクセスしなければならない。
+ * @return パース対象文字列
+ */
+ DecodedContent getContent();
+
+ /**
+ * 現時点での正規表現マッチャを得る。
+ * このクラスおよびこのクラスを継承するものは、
+ * 全てこのメソッドを介してマッチャにアクセスしなければならない。
+ * @return 正規表現マッチャ
+ */
+ Matcher getMatcher();
+
+}
-/*\r
- * abstract content builder\r
- *\r
- * License : The MIT License\r
- * Copyright(c) 2009 olyutorskii\r
- */\r
-\r
-package jp.sourceforge.jindolf.parser;\r
-\r
-import java.nio.charset.CharsetDecoder;\r
-\r
-/**\r
- * {@link DecodedContent}取得用抽象デコードハンドラ。\r
- */\r
-public abstract class ContentBuilder implements DecodeHandler{\r
-\r
- /** 文字列内容。 */\r
- private final DecodedContent content;\r
-\r
-\r
- /**\r
- * コンストラクタ。\r
- * 長さ0で空の{@link DecodedContent}がセットされる。\r
- * @param capacity 初期容量\r
- * @throws NegativeArraySizeException 容量指定が負。\r
- */\r
- protected ContentBuilder(int capacity) throws NegativeArraySizeException{\r
- super();\r
- this.content = new DecodedContent(capacity);\r
- return;\r
- }\r
-\r
- /**\r
- * デコード処理の初期化。\r
- */\r
- protected void init(){\r
- return;\r
- }\r
-\r
- /**\r
- * エラー情報をフラッシュする。\r
- */\r
- protected void flushError(){\r
- return;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @param decoder {@inheritDoc}\r
- * @throws DecodeException {@inheritDoc}\r
- */\r
- @Override\r
- public void startDecoding(CharsetDecoder decoder)\r
- throws DecodeException{\r
- init();\r
- return;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @throws DecodeException {@inheritDoc}\r
- */\r
- @Override\r
- public void endDecoding()\r
- throws DecodeException{\r
- flushError();\r
- return;\r
- }\r
-\r
- /**\r
- * デコード結果の{@link DecodedContent}を取得する。\r
- * @return デコード結果文字列\r
- */\r
- public DecodedContent getContent(){\r
- return this.content;\r
- }\r
-\r
-}\r
+/*
+ * abstract content builder
+ *
+ * License : The MIT License
+ * Copyright(c) 2009 olyutorskii
+ */
+
+package jp.sourceforge.jindolf.parser;
+
+import java.nio.charset.CharsetDecoder;
+
+/**
+ * {@link DecodedContent}取得用抽象デコードハンドラ。
+ */
+public abstract class ContentBuilder implements DecodeHandler{
+
+ /** 文字列内容。 */
+ private final DecodedContent content;
+
+
+ /**
+ * コンストラクタ。
+ * 長さ0で空の{@link DecodedContent}がセットされる。
+ * @param capacity 初期容量
+ * @throws NegativeArraySizeException 容量指定が負。
+ */
+ protected ContentBuilder(int capacity) throws NegativeArraySizeException{
+ super();
+ this.content = new DecodedContent(capacity);
+ return;
+ }
+
+ /**
+ * デコード処理の初期化。
+ */
+ protected void init(){
+ return;
+ }
+
+ /**
+ * エラー情報をフラッシュする。
+ */
+ protected void flushError(){
+ return;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @param decoder {@inheritDoc}
+ * @throws DecodeException {@inheritDoc}
+ */
+ @Override
+ public void startDecoding(CharsetDecoder decoder)
+ throws DecodeException{
+ init();
+ return;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @throws DecodeException {@inheritDoc}
+ */
+ @Override
+ public void endDecoding()
+ throws DecodeException{
+ flushError();
+ return;
+ }
+
+ /**
+ * デコード結果の{@link DecodedContent}を取得する。
+ * @return デコード結果文字列
+ */
+ public DecodedContent getContent(){
+ return this.content;
+ }
+
+}
-/*\r
- * content builder for Shift_JIS\r
- *\r
- * License : The MIT License\r
- * Copyright(c) 2009 olyutorskii\r
- */\r
-\r
-package jp.sourceforge.jindolf.parser;\r
-\r
-/**\r
- * "Shift_JIS"エンコーディング用デコードハンドラ。\r
- * {@link SjisDecoder}からの通知に従い、\r
- * {@link DecodedContent}へとデコードする。\r
- */\r
-public class ContentBuilderSJ extends ContentBuilder{\r
-\r
- private static final int DEF_BUF_SZ = 128;\r
-\r
-\r
- private boolean hasByte1st;\r
- private byte byte1st;\r
-\r
-\r
- /**\r
- * コンストラクタ。\r
- * 長さ0で空の{@link DecodedContent}がセットされる。\r
- */\r
- public ContentBuilderSJ(){\r
- this(DEF_BUF_SZ);\r
- return;\r
- }\r
-\r
- /**\r
- * コンストラクタ。\r
- * 長さ0で空の{@link DecodedContent}がセットされる。\r
- * @param capacity 初期容量\r
- * @throws NegativeArraySizeException 容量指定が負。\r
- */\r
- public ContentBuilderSJ(int capacity) throws NegativeArraySizeException{\r
- super(capacity);\r
- initImpl();\r
- return;\r
- }\r
-\r
- /**\r
- * デコード処理の初期化下請。\r
- */\r
- private void initImpl(){\r
- getContent().init();\r
- this.hasByte1st = false;\r
- this.byte1st = 0x00;\r
- return;\r
- }\r
-\r
- /**\r
- * デコード処理の初期化。\r
- */\r
- @Override\r
- protected void init(){\r
- initImpl();\r
- return;\r
- }\r
-\r
- /**\r
- * エラー情報をフラッシュする。\r
- */\r
- @Override\r
- protected void flushError(){\r
- if(this.hasByte1st){\r
- getContent().addDecodeError(this.byte1st);\r
- this.hasByte1st = false;\r
- }\r
- return;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @param seq {@inheritDoc}\r
- * @throws DecodeException {@inheritDoc}\r
- */\r
- @Override\r
- public void charContent(CharSequence seq)\r
- throws DecodeException{\r
- flushError();\r
- getContent().append(seq);\r
- return;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @param errorArray {@inheritDoc}\r
- * @param offset {@inheritDoc}\r
- * @param length {@inheritDoc}\r
- * @throws DecodeException {@inheritDoc}\r
- */\r
- @Override\r
- public void decodingError(byte[] errorArray, int offset, int length)\r
- throws DecodeException{\r
- int limit = offset + length;\r
- for(int bpos = offset; bpos < limit; bpos++){\r
- byte bval = errorArray[bpos];\r
- if( ! this.hasByte1st){\r
- if(ShiftJis.isShiftJIS1stByte(bval)){\r
- this.byte1st = bval;\r
- this.hasByte1st = true;\r
- }else{\r
- getContent().addDecodeError(bval);\r
- }\r
- }else{\r
- if(ShiftJis.isShiftJIS2ndByte(bval)){ // 文字集合エラー\r
- getContent().addDecodeError(this.byte1st, bval);\r
- this.hasByte1st = false;\r
- }else if(ShiftJis.isShiftJIS1stByte(bval)){\r
- getContent().addDecodeError(this.byte1st);\r
- this.byte1st = bval;\r
- this.hasByte1st = true;\r
- }else{\r
- getContent().addDecodeError(this.byte1st);\r
- getContent().addDecodeError(bval);\r
- this.hasByte1st = false;\r
- }\r
- }\r
- }\r
-\r
- return;\r
- }\r
-\r
-}\r
+/*
+ * content builder for Shift_JIS
+ *
+ * License : The MIT License
+ * Copyright(c) 2009 olyutorskii
+ */
+
+package jp.sourceforge.jindolf.parser;
+
+/**
+ * "Shift_JIS"エンコーディング用デコードハンドラ。
+ * {@link SjisDecoder}からの通知に従い、
+ * {@link DecodedContent}へとデコードする。
+ */
+public class ContentBuilderSJ extends ContentBuilder{
+
+ private static final int DEF_BUF_SZ = 128;
+
+
+ private boolean hasByte1st;
+ private byte byte1st;
+
+
+ /**
+ * コンストラクタ。
+ * 長さ0で空の{@link DecodedContent}がセットされる。
+ */
+ public ContentBuilderSJ(){
+ this(DEF_BUF_SZ);
+ return;
+ }
+
+ /**
+ * コンストラクタ。
+ * 長さ0で空の{@link DecodedContent}がセットされる。
+ * @param capacity 初期容量
+ * @throws NegativeArraySizeException 容量指定が負。
+ */
+ public ContentBuilderSJ(int capacity) throws NegativeArraySizeException{
+ super(capacity);
+ initImpl();
+ return;
+ }
+
+ /**
+ * デコード処理の初期化下請。
+ */
+ private void initImpl(){
+ getContent().init();
+ this.hasByte1st = false;
+ this.byte1st = 0x00;
+ return;
+ }
+
+ /**
+ * デコード処理の初期化。
+ */
+ @Override
+ protected void init(){
+ initImpl();
+ return;
+ }
+
+ /**
+ * エラー情報をフラッシュする。
+ */
+ @Override
+ protected void flushError(){
+ if(this.hasByte1st){
+ getContent().addDecodeError(this.byte1st);
+ this.hasByte1st = false;
+ }
+ return;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @param seq {@inheritDoc}
+ * @throws DecodeException {@inheritDoc}
+ */
+ @Override
+ public void charContent(CharSequence seq)
+ throws DecodeException{
+ flushError();
+ getContent().append(seq);
+ return;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @param errorArray {@inheritDoc}
+ * @param offset {@inheritDoc}
+ * @param length {@inheritDoc}
+ * @throws DecodeException {@inheritDoc}
+ */
+ @Override
+ public void decodingError(byte[] errorArray, int offset, int length)
+ throws DecodeException{
+ int limit = offset + length;
+ for(int bpos = offset; bpos < limit; bpos++){
+ byte bval = errorArray[bpos];
+ if( ! this.hasByte1st){
+ if(ShiftJis.isShiftJIS1stByte(bval)){
+ this.byte1st = bval;
+ this.hasByte1st = true;
+ }else{
+ getContent().addDecodeError(bval);
+ }
+ }else{
+ if(ShiftJis.isShiftJIS2ndByte(bval)){ // 文字集合エラー
+ getContent().addDecodeError(this.byte1st, bval);
+ this.hasByte1st = false;
+ }else if(ShiftJis.isShiftJIS1stByte(bval)){
+ getContent().addDecodeError(this.byte1st);
+ this.byte1st = bval;
+ this.hasByte1st = true;
+ }else{
+ getContent().addDecodeError(this.byte1st);
+ getContent().addDecodeError(bval);
+ this.hasByte1st = false;
+ }
+ }
+ }
+
+ return;
+ }
+
+}
-/*\r
- * content builder for UTF-8 (UCS2 only)\r
- *\r
- * License : The MIT License\r
- * Copyright(c) 2010 olyutorskii\r
- */\r
-\r
-package jp.sourceforge.jindolf.parser;\r
-\r
-/**\r
- * "UTF-8"エンコーディング用デコードハンドラ。\r
- * {@link StreamDecoder}からの通知に従い、\r
- * {@link DecodedContent}へとデコードする。\r
- * UCS-4はUTF-16エラー扱い。\r
- */\r
-public class ContentBuilderUCS2 extends ContentBuilder{\r
-\r
- private static final int DEF_BUF_SZ = 128;\r
-\r
-\r
- /**\r
- * コンストラクタ。\r
- * 長さ0で空の{@link DecodedContent}がセットされる。\r
- */\r
- public ContentBuilderUCS2(){\r
- this(DEF_BUF_SZ);\r
- return;\r
- }\r
-\r
- /**\r
- * コンストラクタ。\r
- * 長さ0で空の{@link DecodedContent}がセットされる。\r
- * @param capacity 初期容量\r
- * @throws NegativeArraySizeException 容量指定が負。\r
- */\r
- public ContentBuilderUCS2(int capacity)\r
- throws NegativeArraySizeException{\r
- super(capacity);\r
- initImpl();\r
- return;\r
- }\r
-\r
-\r
- /**\r
- * サロゲートペア文字(上位,下位)をUTF-16BEバイト列に変換する。\r
- * @param ch 文字\r
- * @return UTF-8バイト列\r
- */\r
- public static byte[] charToUTF16(char ch){\r
- byte[] result = new byte[2];\r
- result[0] = (byte)(ch >> 8);\r
- result[1] = (byte)(ch & 0xff);\r
-\r
- return result;\r
- }\r
-\r
-\r
- /**\r
- * デコード処理の初期化下請。\r
- */\r
- private void initImpl(){\r
- this.getContent().init();\r
- return;\r
- }\r
-\r
- /**\r
- * デコード処理の初期化。\r
- */\r
- @Override\r
- protected void init(){\r
- initImpl();\r
- return;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @param seq {@inheritDoc}\r
- * @throws DecodeException {@inheritDoc}\r
- */\r
- @Override\r
- public void charContent(CharSequence seq)\r
- throws DecodeException{\r
- flushError();\r
-\r
- int length = seq.length();\r
- int startPos = 0;\r
-\r
- for(int pos = 0; pos < length; pos++){\r
- char ch = seq.charAt(pos);\r
-\r
- if( ! Character.isHighSurrogate(ch)\r
- && ! Character.isLowSurrogate (ch) ){\r
- continue;\r
- }\r
-\r
- if(startPos < pos){\r
- CharSequence chopped = seq.subSequence(startPos, pos);\r
- getContent().append(chopped);\r
- startPos = pos + 1;\r
- }\r
-\r
- byte[] barr = charToUTF16(ch);\r
- for(byte bval : barr){\r
- getContent().addDecodeError(bval);\r
- }\r
- }\r
-\r
- if(startPos < length){\r
- CharSequence chopped = seq.subSequence(startPos, length);\r
- getContent().append(chopped);\r
- }\r
-\r
- return;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @param errorArray {@inheritDoc}\r
- * @param offset {@inheritDoc}\r
- * @param length {@inheritDoc}\r
- * @throws DecodeException {@inheritDoc}\r
- */\r
- @Override\r
- public void decodingError(byte[] errorArray, int offset, int length)\r
- throws DecodeException{\r
- int limit = offset + length;\r
-\r
- for(int bpos = offset; bpos < limit; bpos++){\r
- byte bval = errorArray[bpos];\r
- getContent().addDecodeError(bval);\r
- }\r
-\r
- return;\r
- }\r
-\r
-}\r
+/*
+ * content builder for UTF-8 (UCS2 only)
+ *
+ * License : The MIT License
+ * Copyright(c) 2010 olyutorskii
+ */
+
+package jp.sourceforge.jindolf.parser;
+
+/**
+ * "UTF-8"エンコーディング用デコードハンドラ。
+ * {@link StreamDecoder}からの通知に従い、
+ * {@link DecodedContent}へとデコードする。
+ * UCS-4はUTF-16エラー扱い。
+ */
+public class ContentBuilderUCS2 extends ContentBuilder{
+
+ private static final int DEF_BUF_SZ = 128;
+
+
+ /**
+ * コンストラクタ。
+ * 長さ0で空の{@link DecodedContent}がセットされる。
+ */
+ public ContentBuilderUCS2(){
+ this(DEF_BUF_SZ);
+ return;
+ }
+
+ /**
+ * コンストラクタ。
+ * 長さ0で空の{@link DecodedContent}がセットされる。
+ * @param capacity 初期容量
+ * @throws NegativeArraySizeException 容量指定が負。
+ */
+ public ContentBuilderUCS2(int capacity)
+ throws NegativeArraySizeException{
+ super(capacity);
+ initImpl();
+ return;
+ }
+
+
+ /**
+ * サロゲートペア文字(上位,下位)をUTF-16BEバイト列に変換する。
+ * @param ch 文字
+ * @return UTF-8バイト列
+ */
+ public static byte[] charToUTF16(char ch){
+ byte[] result = new byte[2];
+ result[0] = (byte)(ch >> 8);
+ result[1] = (byte)(ch & 0xff);
+
+ return result;
+ }
+
+
+ /**
+ * デコード処理の初期化下請。
+ */
+ private void initImpl(){
+ this.getContent().init();
+ return;
+ }
+
+ /**
+ * デコード処理の初期化。
+ */
+ @Override
+ protected void init(){
+ initImpl();
+ return;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @param seq {@inheritDoc}
+ * @throws DecodeException {@inheritDoc}
+ */
+ @Override
+ public void charContent(CharSequence seq)
+ throws DecodeException{
+ flushError();
+
+ int length = seq.length();
+ int startPos = 0;
+
+ for(int pos = 0; pos < length; pos++){
+ char ch = seq.charAt(pos);
+
+ if( ! Character.isHighSurrogate(ch)
+ && ! Character.isLowSurrogate (ch) ){
+ continue;
+ }
+
+ if(startPos < pos){
+ CharSequence chopped = seq.subSequence(startPos, pos);
+ getContent().append(chopped);
+ startPos = pos + 1;
+ }
+
+ byte[] barr = charToUTF16(ch);
+ for(byte bval : barr){
+ getContent().addDecodeError(bval);
+ }
+ }
+
+ if(startPos < length){
+ CharSequence chopped = seq.subSequence(startPos, length);
+ getContent().append(chopped);
+ }
+
+ return;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @param errorArray {@inheritDoc}
+ * @param offset {@inheritDoc}
+ * @param length {@inheritDoc}
+ * @throws DecodeException {@inheritDoc}
+ */
+ @Override
+ public void decodingError(byte[] errorArray, int offset, int length)
+ throws DecodeException{
+ int limit = offset + length;
+
+ for(int bpos = offset; bpos < limit; bpos++){
+ byte bval = errorArray[bpos];
+ getContent().addDecodeError(bval);
+ }
+
+ return;
+ }
+
+}
-/*\r
- * invalid Shift_JIS decoding information\r
- *\r
- * License : The MIT License\r
- * Copyright(c) 2009 olyutorskii\r
- */\r
-\r
-package jp.sourceforge.jindolf.parser;\r
-\r
-import java.util.Comparator;\r
-\r
-/**\r
- * 不正な Shift_JIS デコードの情報。\r
- * 1バイトもしくは2バイトで構成される。\r
- * 1バイトの場合はおそらくエンコーディングに関するエラー。\r
- * 2バイトの場合はおそらく文字集合に関するエラー。\r
- */\r
-public class DecodeErrorInfo{\r
-\r
- /** 出現位置順Comparator。 */\r
- public static final Comparator<DecodeErrorInfo> POS_COMPARATOR =\r
- new PosComparator();\r
-\r
- private final int charPos;\r
- private final boolean has2ndFlag;\r
- private final byte rawByte1st;\r
- private final byte rawByte2nd;\r
-\r
- /**\r
- * 下請けコンストラクタ。\r
- * @param charPos デコードエラーで置き換えられた文字列の開始位置\r
- * @param has2ndFlag 2バイト目が有効ならtrueを渡す。\r
- * @param rawByte1st デコードエラーを引き起こした最初のバイト値\r
- * @param rawByte2nd デコードエラーを引き起こした2番目のバイト値\r
- * @throws IndexOutOfBoundsException charPosが負\r
- */\r
- private DecodeErrorInfo(int charPos,\r
- boolean has2ndFlag,\r
- byte rawByte1st,\r
- byte rawByte2nd)\r
- throws IndexOutOfBoundsException{\r
- if(charPos < 0) throw new IndexOutOfBoundsException();\r
-\r
- this.charPos = charPos;\r
- this.has2ndFlag = has2ndFlag;\r
- this.rawByte1st = rawByte1st;\r
- this.rawByte2nd = rawByte2nd;\r
-\r
- return;\r
- }\r
-\r
- /**\r
- * コンストラクタ。\r
- * @param charPos デコードエラーで置き換えられた文字列の開始位置\r
- * @param rawByte1st デコードエラーを引き起こした最初のバイト値\r
- * @param rawByte2nd デコードエラーを引き起こした2番目のバイト値\r
- * @throws IndexOutOfBoundsException charPosが負\r
- */\r
- public DecodeErrorInfo(int charPos,\r
- byte rawByte1st,\r
- byte rawByte2nd)\r
- throws IndexOutOfBoundsException{\r
- this(charPos, true, rawByte1st, rawByte2nd);\r
- return;\r
- }\r
-\r
- /**\r
- * コンストラクタ。\r
- * @param charPos デコードエラーで置き換えられた文字列の開始位置\r
- * @param rawByte1st デコードエラーを引き起こしたバイト値\r
- * @throws IndexOutOfBoundsException charPosが負\r
- */\r
- public DecodeErrorInfo(int charPos,\r
- byte rawByte1st)\r
- throws IndexOutOfBoundsException{\r
- this(charPos, false, rawByte1st, (byte)0x00);\r
- return;\r
- }\r
-\r
- /**\r
- * デコードエラーで置き換えられた文字列の開始位置を返す。\r
- * @return デコードエラーで置き換えられた文字列の開始位置\r
- */\r
- public int getCharPosition(){\r
- return this.charPos;\r
- }\r
-\r
- /**\r
- * 2バイト目の情報を持つか判定する。\r
- * @return 2バイト目の情報を持つならtrue\r
- */\r
- public boolean has2nd(){\r
- return this.has2ndFlag;\r
- }\r
-\r
- /**\r
- * 1バイト目の値を返す。\r
- * @return 1バイト目の値\r
- */\r
- public byte getRawByte1st(){\r
- return this.rawByte1st;\r
- }\r
-\r
- /**\r
- * 2バイト目の値を返す。\r
- * @return 2バイト目の値\r
- * @throws IllegalStateException 2バイト目の情報を把持していないとき\r
- */\r
- public byte getRawByte2nd() throws IllegalStateException{\r
- if( ! this.has2ndFlag ) throw new IllegalStateException();\r
- return this.rawByte2nd;\r
- }\r
-\r
- /**\r
- * 出現位置のみが違う複製オブジェクトを生成する。\r
- * @param gap 出現位置から引きたい値。正の値なら文字開始位置に向かう。\r
- * @return 複製オブジェクト\r
- * @throws IndexOutOfBoundsException 再計算された出現位置が負\r
- */\r
- public DecodeErrorInfo createGappedClone(int gap)\r
- throws IndexOutOfBoundsException{\r
- DecodeErrorInfo result;\r
-\r
- int newPos = this.charPos - gap;\r
- if(this.has2ndFlag){\r
- result = new DecodeErrorInfo(newPos,\r
- this.rawByte1st, this.rawByte2nd);\r
- }else{\r
- result = new DecodeErrorInfo(newPos, this.rawByte1st);\r
- }\r
-\r
- return result;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @return {@inheritDoc}\r
- */\r
- @Override\r
- public String toString(){\r
- StringBuilder result = new StringBuilder();\r
-\r
- result.append("start:").append(this.charPos).append(' ');\r
-\r
- String hex;\r
- hex = Integer.toHexString(this.rawByte1st & 0xff);\r
- if(hex.length() <= 1) result.append('0');\r
- result.append(hex);\r
-\r
- if(this.has2ndFlag){\r
- hex = Integer.toHexString(this.rawByte2nd & 0xff);\r
- result.append(':');\r
- if(hex.length() <= 1) result.append('0');\r
- result.append(hex);\r
- }\r
-\r
- return result.toString();\r
- }\r
-\r
- /**\r
- * 出現位置で順序づける比較子。\r
- */\r
- private static final class PosComparator\r
- implements Comparator<DecodeErrorInfo> {\r
-\r
- /**\r
- * コンストラクタ。\r
- */\r
- private PosComparator(){\r
- super();\r
- return;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @param info1 {@inheritDoc}\r
- * @param info2 {@inheritDoc}\r
- * @return {@inheritDoc}\r
- */\r
- @Override\r
- public int compare(DecodeErrorInfo info1, DecodeErrorInfo info2){\r
- int pos1;\r
- int pos2;\r
-\r
- if(info1 == null) pos1 = -1;\r
- else pos1 = info1.charPos;\r
-\r
- if(info2 == null) pos2 = -1;\r
- else pos2 = info2.charPos;\r
-\r
- return pos1 - pos2;\r
- }\r
-\r
- }\r
-\r
-}\r
+/*
+ * invalid Shift_JIS decoding information
+ *
+ * License : The MIT License
+ * Copyright(c) 2009 olyutorskii
+ */
+
+package jp.sourceforge.jindolf.parser;
+
+import java.util.Comparator;
+
+/**
+ * 不正な Shift_JIS デコードの情報。
+ * 1バイトもしくは2バイトで構成される。
+ * 1バイトの場合はおそらくエンコーディングに関するエラー。
+ * 2バイトの場合はおそらく文字集合に関するエラー。
+ */
+public class DecodeErrorInfo{
+
+ /** 出現位置順Comparator。 */
+ public static final Comparator<DecodeErrorInfo> POS_COMPARATOR =
+ new PosComparator();
+
+ private final int charPos;
+ private final boolean has2ndFlag;
+ private final byte rawByte1st;
+ private final byte rawByte2nd;
+
+ /**
+ * 下請けコンストラクタ。
+ * @param charPos デコードエラーで置き換えられた文字列の開始位置
+ * @param has2ndFlag 2バイト目が有効ならtrueを渡す。
+ * @param rawByte1st デコードエラーを引き起こした最初のバイト値
+ * @param rawByte2nd デコードエラーを引き起こした2番目のバイト値
+ * @throws IndexOutOfBoundsException charPosが負
+ */
+ private DecodeErrorInfo(int charPos,
+ boolean has2ndFlag,
+ byte rawByte1st,
+ byte rawByte2nd)
+ throws IndexOutOfBoundsException{
+ if(charPos < 0) throw new IndexOutOfBoundsException();
+
+ this.charPos = charPos;
+ this.has2ndFlag = has2ndFlag;
+ this.rawByte1st = rawByte1st;
+ this.rawByte2nd = rawByte2nd;
+
+ return;
+ }
+
+ /**
+ * コンストラクタ。
+ * @param charPos デコードエラーで置き換えられた文字列の開始位置
+ * @param rawByte1st デコードエラーを引き起こした最初のバイト値
+ * @param rawByte2nd デコードエラーを引き起こした2番目のバイト値
+ * @throws IndexOutOfBoundsException charPosが負
+ */
+ public DecodeErrorInfo(int charPos,
+ byte rawByte1st,
+ byte rawByte2nd)
+ throws IndexOutOfBoundsException{
+ this(charPos, true, rawByte1st, rawByte2nd);
+ return;
+ }
+
+ /**
+ * コンストラクタ。
+ * @param charPos デコードエラーで置き換えられた文字列の開始位置
+ * @param rawByte1st デコードエラーを引き起こしたバイト値
+ * @throws IndexOutOfBoundsException charPosが負
+ */
+ public DecodeErrorInfo(int charPos,
+ byte rawByte1st)
+ throws IndexOutOfBoundsException{
+ this(charPos, false, rawByte1st, (byte)0x00);
+ return;
+ }
+
+ /**
+ * デコードエラーで置き換えられた文字列の開始位置を返す。
+ * @return デコードエラーで置き換えられた文字列の開始位置
+ */
+ public int getCharPosition(){
+ return this.charPos;
+ }
+
+ /**
+ * 2バイト目の情報を持つか判定する。
+ * @return 2バイト目の情報を持つならtrue
+ */
+ public boolean has2nd(){
+ return this.has2ndFlag;
+ }
+
+ /**
+ * 1バイト目の値を返す。
+ * @return 1バイト目の値
+ */
+ public byte getRawByte1st(){
+ return this.rawByte1st;
+ }
+
+ /**
+ * 2バイト目の値を返す。
+ * @return 2バイト目の値
+ * @throws IllegalStateException 2バイト目の情報を把持していないとき
+ */
+ public byte getRawByte2nd() throws IllegalStateException{
+ if( ! this.has2ndFlag ) throw new IllegalStateException();
+ return this.rawByte2nd;
+ }
+
+ /**
+ * 出現位置のみが違う複製オブジェクトを生成する。
+ * @param gap 出現位置から引きたい値。正の値なら文字開始位置に向かう。
+ * @return 複製オブジェクト
+ * @throws IndexOutOfBoundsException 再計算された出現位置が負
+ */
+ public DecodeErrorInfo createGappedClone(int gap)
+ throws IndexOutOfBoundsException{
+ DecodeErrorInfo result;
+
+ int newPos = this.charPos - gap;
+ if(this.has2ndFlag){
+ result = new DecodeErrorInfo(newPos,
+ this.rawByte1st, this.rawByte2nd);
+ }else{
+ result = new DecodeErrorInfo(newPos, this.rawByte1st);
+ }
+
+ return result;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @return {@inheritDoc}
+ */
+ @Override
+ public String toString(){
+ StringBuilder result = new StringBuilder();
+
+ result.append("start:").append(this.charPos).append(' ');
+
+ String hex;
+ hex = Integer.toHexString(this.rawByte1st & 0xff);
+ if(hex.length() <= 1) result.append('0');
+ result.append(hex);
+
+ if(this.has2ndFlag){
+ hex = Integer.toHexString(this.rawByte2nd & 0xff);
+ result.append(':');
+ if(hex.length() <= 1) result.append('0');
+ result.append(hex);
+ }
+
+ return result.toString();
+ }
+
+ /**
+ * 出現位置で順序づける比較子。
+ */
+ private static final class PosComparator
+ implements Comparator<DecodeErrorInfo> {
+
+ /**
+ * コンストラクタ。
+ */
+ private PosComparator(){
+ super();
+ return;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @param info1 {@inheritDoc}
+ * @param info2 {@inheritDoc}
+ * @return {@inheritDoc}
+ */
+ @Override
+ public int compare(DecodeErrorInfo info1, DecodeErrorInfo info2){
+ int pos1;
+ int pos2;
+
+ if(info1 == null) pos1 = -1;
+ else pos1 = info1.charPos;
+
+ if(info2 == null) pos2 = -1;
+ else pos2 = info2.charPos;
+
+ return pos1 - pos2;
+ }
+
+ }
+
+}
-/*\r
- * decode exception\r
- *\r
- * License : The MIT License\r
- * Copyright(c) 2009 olyutorskii\r
- */\r
-\r
-package jp.sourceforge.jindolf.parser;\r
-\r
-/**\r
- * デコード異常系情報。\r
- * {@link DecodeHandler}の各メソッドは、この例外をスローすることで\r
- * デコード処理の即時停止を{@link StreamDecoder}に指示することができる。\r
- * デコード元(バイトストリーム)の中のエラー発生位置と\r
- * デコード先(CharSequence)の中のエラー発生位置を保持することができる。\r
- * いずれの値も、エラー発生位置が不明な場合は負の値が設定される。\r
- */\r
-@SuppressWarnings("serial")\r
-public class DecodeException extends Exception{\r
-\r
- private final int bytePos;\r
- private final int charPos;\r
-\r
- /**\r
- * コンストラクタ。\r
- */\r
- public DecodeException(){\r
- this(null);\r
- return;\r
- }\r
-\r
- /**\r
- * コンストラクタ。\r
- * @param message メッセージ\r
- */\r
- public DecodeException(String message){\r
- this(message, -1, -1);\r
- return;\r
- }\r
-\r
- /**\r
- * コンストラクタ。\r
- * 位置情報が不明な場合は負の値を渡す。\r
- * @param bytePos デコード元エラー発生バイト位置\r
- * @param charPos デコード先エラー発生文字位置\r
- */\r
- public DecodeException(int bytePos, int charPos){\r
- this(null, bytePos, charPos);\r
- return;\r
- }\r
-\r
- /**\r
- * コンストラクタ。\r
- * 位置情報が不明な場合は負の値を渡す。\r
- * @param message メッセージ\r
- * @param bytePos デコード元エラー発生バイト位置\r
- * @param charPos デコード先エラー発生文字位置\r
- */\r
- public DecodeException(String message, int bytePos, int charPos){\r
- super(message);\r
- this.bytePos = bytePos;\r
- this.charPos = charPos;\r
- return;\r
- }\r
-\r
- /**\r
- * デコード元エラー発生位置を返す。\r
- * 単位はbyte単位。\r
- * @return エラー発生位置。不明な場合は負の値。\r
- */\r
- public int getBytePos(){\r
- return this.bytePos;\r
- }\r
-\r
- /**\r
- * デコード先エラー発生位置を返す。\r
- * 単位はchar単位。\r
- * @return エラー発生位置。不明な場合は負の値。\r
- */\r
- public int getCharPos(){\r
- return this.charPos;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @return {@inheritDoc}\r
- */\r
- @Override\r
- public String getMessage(){\r
- StringBuilder result = new StringBuilder();\r
-\r
- String message = super.getMessage();\r
- if(message != null && message.length() > 0){\r
- result.append(message).append(' ');\r
- }\r
-\r
- result.append("bytePos=").append(this.bytePos);\r
- result.append(' ');\r
- result.append("charPos=").append(this.charPos);\r
-\r
- return result.toString();\r
- }\r
-\r
-}\r
+/*
+ * decode exception
+ *
+ * License : The MIT License
+ * Copyright(c) 2009 olyutorskii
+ */
+
+package jp.sourceforge.jindolf.parser;
+
+/**
+ * デコード異常系情報。
+ * {@link DecodeHandler}の各メソッドは、この例外をスローすることで
+ * デコード処理の即時停止を{@link StreamDecoder}に指示することができる。
+ * デコード元(バイトストリーム)の中のエラー発生位置と
+ * デコード先(CharSequence)の中のエラー発生位置を保持することができる。
+ * いずれの値も、エラー発生位置が不明な場合は負の値が設定される。
+ */
+@SuppressWarnings("serial")
+public class DecodeException extends Exception{
+
+ private final int bytePos;
+ private final int charPos;
+
+ /**
+ * コンストラクタ。
+ */
+ public DecodeException(){
+ this(null);
+ return;
+ }
+
+ /**
+ * コンストラクタ。
+ * @param message メッセージ
+ */
+ public DecodeException(String message){
+ this(message, -1, -1);
+ return;
+ }
+
+ /**
+ * コンストラクタ。
+ * 位置情報が不明な場合は負の値を渡す。
+ * @param bytePos デコード元エラー発生バイト位置
+ * @param charPos デコード先エラー発生文字位置
+ */
+ public DecodeException(int bytePos, int charPos){
+ this(null, bytePos, charPos);
+ return;
+ }
+
+ /**
+ * コンストラクタ。
+ * 位置情報が不明な場合は負の値を渡す。
+ * @param message メッセージ
+ * @param bytePos デコード元エラー発生バイト位置
+ * @param charPos デコード先エラー発生文字位置
+ */
+ public DecodeException(String message, int bytePos, int charPos){
+ super(message);
+ this.bytePos = bytePos;
+ this.charPos = charPos;
+ return;
+ }
+
+ /**
+ * デコード元エラー発生位置を返す。
+ * 単位はbyte単位。
+ * @return エラー発生位置。不明な場合は負の値。
+ */
+ public int getBytePos(){
+ return this.bytePos;
+ }
+
+ /**
+ * デコード先エラー発生位置を返す。
+ * 単位はchar単位。
+ * @return エラー発生位置。不明な場合は負の値。
+ */
+ public int getCharPos(){
+ return this.charPos;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @return {@inheritDoc}
+ */
+ @Override
+ public String getMessage(){
+ StringBuilder result = new StringBuilder();
+
+ String message = super.getMessage();
+ if(message != null && message.length() > 0){
+ result.append(message).append(' ');
+ }
+
+ result.append("bytePos=").append(this.bytePos);
+ result.append(' ');
+ result.append("charPos=").append(this.charPos);
+
+ return result.toString();
+ }
+
+}
-/*\r
- * decode handler\r
- *\r
- * License : The MIT License\r
- * Copyright(c) 2009 olyutorskii\r
- */\r
-\r
-package jp.sourceforge.jindolf.parser;\r
-\r
-import java.nio.charset.CharsetDecoder;\r
-\r
-/**\r
- * 文字デコードハンドラ。\r
- * {@link StreamDecoder}により呼ばれる。\r
- * メソッドが呼ばれる順番は\r
- * {@link #startDecoding}が最初で\r
- * {@link #endDecoding}が最後。\r
- * その間、{@link #charContent}\r
- * または{@link #decodingError}が複数回呼ばれる。\r
- * 各メソッドは、{@link DecodeException}をスローすることで\r
- * デコード処理を中止させることができる。\r
- */\r
-public interface DecodeHandler{\r
-\r
- /**\r
- * デコード開始の通知を受け取る。\r
- * @param decoder デコーダ\r
- * @throws DecodeException デコードエラー\r
- */\r
- void startDecoding(CharsetDecoder decoder)\r
- throws DecodeException;\r
-\r
- /**\r
- * 正常にデコードした文字列の通知を受け取る。\r
- * seqの内容は、ハンドラ呼び出し元で随時変更されうる。\r
- * seqの内容を後々再利用するつもりなら、\r
- * 制御を呼び出し元に戻すまでの間に必要な箇所をコピーする必要がある。\r
- * @param seq 文字列\r
- * @throws DecodeException デコードエラー\r
- */\r
- void charContent(CharSequence seq)\r
- throws DecodeException;\r
-\r
- /**\r
- * デコードエラーの通知を受け取る。\r
- * errorArrayの内容は、ハンドラ呼び出し元で随時変更されうる。\r
- * errorArrayの内容を後々再利用するつもりなら、\r
- * 制御を呼び出し元に戻すまでの間に必要な箇所をコピーする必要がある。\r
- * @param errorArray エラーを引き起こした入力バイトシーケンス。\r
- * @param offset errorArrayに含まれるエラーの開始位置。\r
- * @param length errorArrayに含まれるエラーのバイト長。\r
- * @throws DecodeException デコードエラー\r
- */\r
- void decodingError(byte[] errorArray, int offset, int length)\r
- throws DecodeException;\r
-\r
- /**\r
- * デコード終了の通知を受け取る。\r
- * @throws DecodeException デコードエラー\r
- */\r
- void endDecoding()\r
- throws DecodeException;\r
-\r
-}\r
+/*
+ * decode handler
+ *
+ * License : The MIT License
+ * Copyright(c) 2009 olyutorskii
+ */
+
+package jp.sourceforge.jindolf.parser;
+
+import java.nio.charset.CharsetDecoder;
+
+/**
+ * 文字デコードハンドラ。
+ * {@link StreamDecoder}により呼ばれる。
+ * メソッドが呼ばれる順番は
+ * {@link #startDecoding}が最初で
+ * {@link #endDecoding}が最後。
+ * その間、{@link #charContent}
+ * または{@link #decodingError}が複数回呼ばれる。
+ * 各メソッドは、{@link DecodeException}をスローすることで
+ * デコード処理を中止させることができる。
+ */
+public interface DecodeHandler{
+
+ /**
+ * デコード開始の通知を受け取る。
+ * @param decoder デコーダ
+ * @throws DecodeException デコードエラー
+ */
+ void startDecoding(CharsetDecoder decoder)
+ throws DecodeException;
+
+ /**
+ * 正常にデコードした文字列の通知を受け取る。
+ * seqの内容は、ハンドラ呼び出し元で随時変更されうる。
+ * seqの内容を後々再利用するつもりなら、
+ * 制御を呼び出し元に戻すまでの間に必要な箇所をコピーする必要がある。
+ * @param seq 文字列
+ * @throws DecodeException デコードエラー
+ */
+ void charContent(CharSequence seq)
+ throws DecodeException;
+
+ /**
+ * デコードエラーの通知を受け取る。
+ * errorArrayの内容は、ハンドラ呼び出し元で随時変更されうる。
+ * errorArrayの内容を後々再利用するつもりなら、
+ * 制御を呼び出し元に戻すまでの間に必要な箇所をコピーする必要がある。
+ * @param errorArray エラーを引き起こした入力バイトシーケンス。
+ * @param offset errorArrayに含まれるエラーの開始位置。
+ * @param length errorArrayに含まれるエラーのバイト長。
+ * @throws DecodeException デコードエラー
+ */
+ void decodingError(byte[] errorArray, int offset, int length)
+ throws DecodeException;
+
+ /**
+ * デコード終了の通知を受け取る。
+ * @throws DecodeException デコードエラー
+ */
+ void endDecoding()
+ throws DecodeException;
+
+}
-/*\r
- * decoded source\r
- *\r
- * License : The MIT License\r
- * Copyright(c) 2009 olyutorskii\r
- */\r
-\r
-package jp.sourceforge.jindolf.parser;\r
-\r
-import java.util.ArrayList;\r
-import java.util.Collections;\r
-import java.util.List;\r
-import java.util.RandomAccess;\r
-\r
-/**\r
- * ShiftJISデコードエラー情報を含む再利用可能な文字列。\r
- * デコードエラーを起こした箇所は代替文字{@link #ALTCHAR}で置き換えられる。\r
- * マルチスレッドには非対応。\r
- * UCS-4コードポイントには未対応。\r
- */\r
-public class DecodedContent\r
- implements CharSequence,\r
- Appendable {\r
-\r
- /**\r
- * 代替文字。\r
- * {@literal HTMLで使うなら < や > や & や " や ' はやめて!}\r
- */\r
- public static final char ALTCHAR = '?';\r
-\r
- private static final String NULLTEXT = "null";\r
-\r
- private static final List<DecodeErrorInfo> EMPTY_LIST =\r
- Collections.emptyList();\r
-\r
- private static final int BSEARCH_THRESHOLD = 16;\r
-\r
- static{\r
- assert ALTCHAR != '<';\r
- assert ALTCHAR != '>';\r
- assert ALTCHAR != '&';\r
- assert ALTCHAR != '"';\r
- assert ALTCHAR != '\'';\r
- assert ALTCHAR != '\\';\r
- }\r
-\r
-\r
- private final StringBuilder rawContent = new StringBuilder();\r
-\r
- private List<DecodeErrorInfo> decodeError;\r
-\r
-\r
- /**\r
- * コンストラクタ。\r
- */\r
- public DecodedContent(){\r
- this("");\r
- return;\r
- }\r
-\r
- /**\r
- * コンストラクタ。\r
- * @param seq 初期化文字列\r
- * @throws NullPointerException 引数がnull\r
- */\r
- public DecodedContent(CharSequence seq) throws NullPointerException{\r
- super();\r
- if(seq == null) throw new NullPointerException();\r
- initImpl();\r
- this.rawContent.append(seq);\r
- return;\r
- }\r
-\r
- /**\r
- * コンストラクタ。\r
- * @param capacity 文字数の初期容量\r
- * @throws NegativeArraySizeException 容量が負の値\r
- */\r
- public DecodedContent(int capacity) throws NegativeArraySizeException{\r
- super();\r
- if(capacity < 0) throw new NegativeArraySizeException();\r
- initImpl();\r
- this.rawContent.ensureCapacity(capacity);\r
- return;\r
- }\r
-\r
-\r
- /**\r
- * 与えられた文字位置を含むか、またはそれ以降で最も小さな位置情報を持つ\r
- * デコードエラーのインデックス位置を返す。※リニアサーチ版。\r
- * @param errList デコードエラーのリスト\r
- * @param startPos 文字位置\r
- * @return 0から始まるリスト内の位置。\r
- * 一致する文字位置がなければ挿入ポイント。\r
- */\r
- protected static int lsearchErrorIndex(List<DecodeErrorInfo> errList,\r
- int startPos){\r
- // assert errList instanceof RandomAccess;\r
-\r
- int errSize = errList.size();\r
-\r
- int idx;\r
- for(idx = 0; idx < errSize; idx++){\r
- DecodeErrorInfo einfo = errList.get(idx);\r
- int errPos = einfo.getCharPosition();\r
- if(startPos <= errPos) break;\r
- }\r
-\r
- return idx;\r
- }\r
-\r
- /**\r
- * 与えられた文字位置を含むか、またはそれ以降で最も小さな位置情報を持つ\r
- * デコードエラーのインデックス位置を返す。※バイナリサーチ版。\r
- * @param errList デコードエラーのリスト\r
- * @param startPos 文字位置\r
- * @return 0から始まるリスト内の位置。\r
- * 一致する文字位置がなければ挿入ポイント。\r
- */\r
- protected static int bsearchErrorIndex(List<DecodeErrorInfo> errList,\r
- int startPos){\r
- // assert errList instanceof RandomAccess;\r
-\r
- int floor = 0;\r
- int roof = errList.size() - 1;\r
-\r
- while(floor <= roof){\r
- int midpoint = (floor + roof) / 2; // 切り捨て\r
- DecodeErrorInfo einfo = errList.get(midpoint);\r
- int cmp = einfo.getCharPosition() - startPos;\r
-\r
- if(cmp == 0) return midpoint;\r
-\r
- if (cmp < 0) floor = midpoint + 1;\r
- else if(cmp > 0) roof = midpoint - 1;\r
- }\r
-\r
- return floor;\r
- }\r
-\r
- /**\r
- * 与えられた文字位置を含むか、またはそれ以降で最も小さな位置情報を持つ\r
- * デコードエラーのインデックス位置を返す。\r
- * 要素数の増減に応じてリニアサーチとバイナリサーチを使い分ける。\r
- * @param errList デコードエラーのリスト\r
- * @param startPos 文字位置\r
- * @return 0から始まるリスト内の位置。\r
- * 一致する文字位置がなければ挿入ポイント。\r
- */\r
- protected static int searchErrorIndex(List<DecodeErrorInfo> errList,\r
- int startPos){\r
- int result;\r
-\r
- int errSize = errList.size();\r
- if(errSize < BSEARCH_THRESHOLD){\r
- // linear-search\r
- result = lsearchErrorIndex(errList, startPos);\r
- }else{\r
- // binary-search\r
- result = bsearchErrorIndex(errList, startPos);\r
- }\r
-\r
- return result;\r
- }\r
-\r
- /**\r
- * ギャップ情報が加味されたデコードエラー情報を、\r
- * 範囲指定込みで指定エラーリストに追加転記する。\r
- * 追加先エラーリストがnullだった場合、必要に応じてエラーリストが生成され\r
- * 戻り値となる場合がありうる。\r
- * @param sourceContent 元の文字列\r
- * @param startPos 範囲開始位置\r
- * @param endPos 範囲終了位置\r
- * @param targetError 追加先エラーリスト。nullでもよい。\r
- * @param gap ギャップ量\r
- * @return 引数targetErrorもしくは新規生成されたリストを返す。\r
- */\r
- protected static List<DecodeErrorInfo>\r
- appendGappedErrorInfo(DecodedContent sourceContent,\r
- int startPos, int endPos,\r
- List<DecodeErrorInfo> targetError,\r
- int gap){\r
- List<DecodeErrorInfo> sourceError = sourceContent.decodeError;\r
- List<DecodeErrorInfo> result = targetError;\r
-\r
- int startErrorIdx = searchErrorIndex(sourceError, startPos);\r
- int endErrorIdx = sourceError.size() - 1;\r
- assert endErrorIdx >= 0;\r
-\r
- for(int index = startErrorIdx; index <= endErrorIdx; index++){\r
- DecodeErrorInfo einfo = sourceError.get(index);\r
- int pos = einfo.getCharPosition();\r
- if(pos < startPos) continue;\r
- if(pos >= endPos) break;\r
- DecodeErrorInfo newInfo = einfo.createGappedClone(gap);\r
- if(result == null){\r
- result = createErrorList();\r
- }\r
- result.add(newInfo);\r
- }\r
-\r
- return result;\r
- }\r
-\r
- /**\r
- * エラー格納用リストを生成する。\r
- * @return リスト\r
- */\r
- private static List<DecodeErrorInfo> createErrorList(){\r
- List<DecodeErrorInfo> result = new ArrayList<DecodeErrorInfo>();\r
- return result;\r
- }\r
-\r
- static{\r
- assert createErrorList() instanceof RandomAccess;\r
- }\r
-\r
- /**\r
- * 初期化下請け。\r
- * 長さ0の文字列&デコードエラー無しの状態になる。\r
- */\r
- private void initImpl(){\r
- this.rawContent.setLength(0);\r
-\r
- if(this.decodeError != null){\r
- this.decodeError.clear();\r
- }\r
-\r
- return;\r
- }\r
-\r
- /**\r
- * 事前にキャパシティを確保する。\r
- * 指定されたキャパシティの範囲内で再割り当てが起きないことを保証する。\r
- * @param minimumCapacity キャラクタ単位のキャパシティ長。\r
- */\r
- public void ensureCapacity(int minimumCapacity){\r
- this.rawContent.ensureCapacity(minimumCapacity);\r
- return;\r
- }\r
-\r
- /**\r
- * 初期化。\r
- * 長さ0の文字列&デコードエラー無しの状態になる。\r
- * コンストラクタで新インスタンスを作るより低コスト。\r
- */\r
- public void init(){\r
- initImpl();\r
- return;\r
- }\r
-\r
- /**\r
- * デコードエラーを含むか判定する。\r
- * @return デコードエラーを含むならtrue\r
- */\r
- public boolean hasDecodeError(){\r
- if(this.decodeError == null) return false;\r
- if(this.decodeError.isEmpty()) return false;\r
- return true;\r
- }\r
-\r
- /**\r
- * デコードエラーの一覧を取得する。\r
- * @return デコードエラーの一覧\r
- */\r
- public List<DecodeErrorInfo> getDecodeErrorList(){\r
- if( ! hasDecodeError() ){\r
- return EMPTY_LIST;\r
- }\r
- return Collections.unmodifiableList(this.decodeError);\r
- }\r
-\r
- /**\r
- * 生の文字列を得る。\r
- * 高速なCharSequenceアクセス用途。\r
- * @return 生の文字列。\r
- */\r
- public CharSequence getRawContent(){\r
- return this.rawContent;\r
- }\r
-\r
- /**\r
- * 指定された位置の文字を変更する。\r
- * @param index 文字位置\r
- * @param ch 文字\r
- * @throws IndexOutOfBoundsException 不正な位置指定\r
- */\r
- public void setCharAt(int index, char ch)\r
- throws IndexOutOfBoundsException{\r
- this.rawContent.setCharAt(index, ch);\r
- return;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @param index {@inheritDoc}\r
- * @return {@inheritDoc}\r
- */\r
- @Override\r
- public char charAt(int index){\r
- return this.rawContent.charAt(index);\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @return {@inheritDoc}\r
- */\r
- @Override\r
- public int length(){\r
- return this.rawContent.length();\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @param start {@inheritDoc}\r
- * @param end {@inheritDoc}\r
- * @return {@inheritDoc}\r
- */\r
- @Override\r
- public CharSequence subSequence(int start, int end){\r
- return this.rawContent.subSequence(start, end);\r
- }\r
-\r
- /**\r
- * 範囲指定されたサブコンテントを切り出す。\r
- * サブコンテントにはデコードエラー情報が引き継がれる。\r
- * @param start 開始位置\r
- * @param end 終了位置\r
- * @return サブコンテント\r
- * @throws IndexOutOfBoundsException start または end が負の値の場合、\r
- * end が length() より大きい場合、あるいは start が end より大きい場合\r
- */\r
- public DecodedContent subContent(int start, int end)\r
- throws IndexOutOfBoundsException{\r
- int length = end - start;\r
- if(length < 0) throw new IndexOutOfBoundsException();\r
- DecodedContent result = new DecodedContent(length);\r
- result.append(this, start, end);\r
- return result;\r
- }\r
-\r
- /**\r
- * 文字を追加する。\r
- * @param letter 追加する文字\r
- * @return thisオブジェクト\r
- */\r
- public DecodedContent append(char letter){\r
- this.rawContent.append(letter);\r
- return this;\r
- }\r
-\r
- /**\r
- * 文字列を追加する。\r
- * @param seq 追加する文字列\r
- * @return thisオブジェクト\r
- */\r
- public DecodedContent append(CharSequence seq){\r
- if(seq == null){\r
- this.rawContent.append(NULLTEXT);\r
- }else if(seq instanceof DecodedContent){\r
- append((DecodedContent)seq, 0, seq.length());\r
- }else{\r
- this.rawContent.append(seq);\r
- }\r
- return this;\r
- }\r
-\r
- /**\r
- * 文字列を追加する。\r
- * @param seq 追加する文字列\r
- * @param startPos 開始位置\r
- * @param endPos 終了位置\r
- * @return thisオブジェクト\r
- * @throws IndexOutOfBoundsException 範囲指定が変。\r
- */\r
- public DecodedContent append(CharSequence seq,\r
- int startPos, int endPos)\r
- throws IndexOutOfBoundsException{\r
- if(seq == null){\r
- this.rawContent.append(NULLTEXT, startPos, endPos);\r
- }else if(seq instanceof DecodedContent){\r
- append((DecodedContent)seq, startPos, endPos);\r
- }else{\r
- this.rawContent.append(seq, startPos, endPos);\r
- }\r
-\r
- return this;\r
- }\r
-\r
- /**\r
- * 文字列を追加する。\r
- * @param source 追加する文字列\r
- * @param startPos 開始位置\r
- * @param endPos 終了位置\r
- * @return thisオブジェクト\r
- * @throws IndexOutOfBoundsException 範囲指定が変。\r
- */\r
- public DecodedContent append(DecodedContent source,\r
- int startPos, int endPos)\r
- throws IndexOutOfBoundsException{\r
- if(source == null){\r
- return append(NULLTEXT, startPos, endPos);\r
- }\r
-\r
- int gap = startPos - this.rawContent.length();\r
-\r
- this.rawContent.append(source.rawContent, startPos, endPos);\r
-\r
- if( ! source.hasDecodeError() ) return this;\r
-\r
- List<DecodeErrorInfo> targetErrorList;\r
- if(source != this) targetErrorList = this.decodeError;\r
- else targetErrorList = null;\r
-\r
- targetErrorList = appendGappedErrorInfo(source,\r
- startPos, endPos,\r
- targetErrorList,\r
- gap);\r
-\r
- if(targetErrorList == null) return this;\r
- if(targetErrorList == this.decodeError) return this;\r
-\r
- if(this.decodeError == null){\r
- this.decodeError = targetErrorList;\r
- }else{\r
- this.decodeError.addAll(targetErrorList);\r
- }\r
-\r
- return this;\r
- }\r
-\r
- /**\r
- * 代替文字とともにデコードエラーを追加する。\r
- * ※呼び出し側は、追加されるデコードエラーの位置情報が\r
- * 既存のデコードエラーよりも大きいことを保証しなければならない。\r
- * @param errorInfo デコードエラー\r
- */\r
- private void addDecodeError(DecodeErrorInfo errorInfo){\r
- if(this.decodeError == null){\r
- this.decodeError = createErrorList();\r
- }\r
- this.decodeError.add(errorInfo);\r
- this.rawContent.append(ALTCHAR);\r
- return;\r
- }\r
-\r
- /**\r
- * 代替文字とともにデコードエラーを追加する。\r
- * @param b1st 1バイト目の値\r
- */\r
- public void addDecodeError(byte b1st){\r
- DecodeErrorInfo errInfo =\r
- new DecodeErrorInfo(this.rawContent.length(), b1st);\r
- addDecodeError(errInfo);\r
- return;\r
- }\r
-\r
- /**\r
- * 代替文字とともにデコードエラーを追加する。\r
- * @param b1st 1バイト目の値\r
- * @param b2nd 2バイト目の値\r
- */\r
- public void addDecodeError(byte b1st, byte b2nd){\r
- DecodeErrorInfo errInfo =\r
- new DecodeErrorInfo(this.rawContent.length(), b1st, b2nd);\r
- addDecodeError(errInfo);\r
- return;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @return {@inheritDoc}\r
- */\r
- @Override\r
- public String toString(){\r
- return this.rawContent.toString();\r
- }\r
-\r
-}\r
+/*
+ * decoded source
+ *
+ * License : The MIT License
+ * Copyright(c) 2009 olyutorskii
+ */
+
+package jp.sourceforge.jindolf.parser;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.RandomAccess;
+
+/**
+ * ShiftJISデコードエラー情報を含む再利用可能な文字列。
+ * デコードエラーを起こした箇所は代替文字{@link #ALTCHAR}で置き換えられる。
+ * マルチスレッドには非対応。
+ * UCS-4コードポイントには未対応。
+ */
+public class DecodedContent
+ implements CharSequence,
+ Appendable {
+
+ /**
+ * 代替文字。
+ * {@literal HTMLで使うなら < や > や & や " や ' はやめて!}
+ */
+ public static final char ALTCHAR = '?';
+
+ private static final String NULLTEXT = "null";
+
+ private static final List<DecodeErrorInfo> EMPTY_LIST =
+ Collections.emptyList();
+
+ private static final int BSEARCH_THRESHOLD = 16;
+
+ static{
+ assert ALTCHAR != '<';
+ assert ALTCHAR != '>';
+ assert ALTCHAR != '&';
+ assert ALTCHAR != '"';
+ assert ALTCHAR != '\'';
+ assert ALTCHAR != '\\';
+ }
+
+
+ private final StringBuilder rawContent = new StringBuilder();
+
+ private List<DecodeErrorInfo> decodeError;
+
+
+ /**
+ * コンストラクタ。
+ */
+ public DecodedContent(){
+ this("");
+ return;
+ }
+
+ /**
+ * コンストラクタ。
+ * @param seq 初期化文字列
+ * @throws NullPointerException 引数がnull
+ */
+ public DecodedContent(CharSequence seq) throws NullPointerException{
+ super();
+ if(seq == null) throw new NullPointerException();
+ initImpl();
+ this.rawContent.append(seq);
+ return;
+ }
+
+ /**
+ * コンストラクタ。
+ * @param capacity 文字数の初期容量
+ * @throws NegativeArraySizeException 容量が負の値
+ */
+ public DecodedContent(int capacity) throws NegativeArraySizeException{
+ super();
+ if(capacity < 0) throw new NegativeArraySizeException();
+ initImpl();
+ this.rawContent.ensureCapacity(capacity);
+ return;
+ }
+
+
+ /**
+ * 与えられた文字位置を含むか、またはそれ以降で最も小さな位置情報を持つ
+ * デコードエラーのインデックス位置を返す。※リニアサーチ版。
+ * @param errList デコードエラーのリスト
+ * @param startPos 文字位置
+ * @return 0から始まるリスト内の位置。
+ * 一致する文字位置がなければ挿入ポイント。
+ */
+ protected static int lsearchErrorIndex(List<DecodeErrorInfo> errList,
+ int startPos){
+ // assert errList instanceof RandomAccess;
+
+ int errSize = errList.size();
+
+ int idx;
+ for(idx = 0; idx < errSize; idx++){
+ DecodeErrorInfo einfo = errList.get(idx);
+ int errPos = einfo.getCharPosition();
+ if(startPos <= errPos) break;
+ }
+
+ return idx;
+ }
+
+ /**
+ * 与えられた文字位置を含むか、またはそれ以降で最も小さな位置情報を持つ
+ * デコードエラーのインデックス位置を返す。※バイナリサーチ版。
+ * @param errList デコードエラーのリスト
+ * @param startPos 文字位置
+ * @return 0から始まるリスト内の位置。
+ * 一致する文字位置がなければ挿入ポイント。
+ */
+ protected static int bsearchErrorIndex(List<DecodeErrorInfo> errList,
+ int startPos){
+ // assert errList instanceof RandomAccess;
+
+ int floor = 0;
+ int roof = errList.size() - 1;
+
+ while(floor <= roof){
+ int midpoint = (floor + roof) / 2; // 切り捨て
+ DecodeErrorInfo einfo = errList.get(midpoint);
+ int cmp = einfo.getCharPosition() - startPos;
+
+ if(cmp == 0) return midpoint;
+
+ if (cmp < 0) floor = midpoint + 1;
+ else if(cmp > 0) roof = midpoint - 1;
+ }
+
+ return floor;
+ }
+
+ /**
+ * 与えられた文字位置を含むか、またはそれ以降で最も小さな位置情報を持つ
+ * デコードエラーのインデックス位置を返す。
+ * 要素数の増減に応じてリニアサーチとバイナリサーチを使い分ける。
+ * @param errList デコードエラーのリスト
+ * @param startPos 文字位置
+ * @return 0から始まるリスト内の位置。
+ * 一致する文字位置がなければ挿入ポイント。
+ */
+ protected static int searchErrorIndex(List<DecodeErrorInfo> errList,
+ int startPos){
+ int result;
+
+ int errSize = errList.size();
+ if(errSize < BSEARCH_THRESHOLD){
+ // linear-search
+ result = lsearchErrorIndex(errList, startPos);
+ }else{
+ // binary-search
+ result = bsearchErrorIndex(errList, startPos);
+ }
+
+ return result;
+ }
+
+ /**
+ * ギャップ情報が加味されたデコードエラー情報を、
+ * 範囲指定込みで指定エラーリストに追加転記する。
+ * 追加先エラーリストがnullだった場合、必要に応じてエラーリストが生成され
+ * 戻り値となる場合がありうる。
+ * @param sourceContent 元の文字列
+ * @param startPos 範囲開始位置
+ * @param endPos 範囲終了位置
+ * @param targetError 追加先エラーリスト。nullでもよい。
+ * @param gap ギャップ量
+ * @return 引数targetErrorもしくは新規生成されたリストを返す。
+ */
+ protected static List<DecodeErrorInfo>
+ appendGappedErrorInfo(DecodedContent sourceContent,
+ int startPos, int endPos,
+ List<DecodeErrorInfo> targetError,
+ int gap){
+ List<DecodeErrorInfo> sourceError = sourceContent.decodeError;
+ List<DecodeErrorInfo> result = targetError;
+
+ int startErrorIdx = searchErrorIndex(sourceError, startPos);
+ int endErrorIdx = sourceError.size() - 1;
+ assert endErrorIdx >= 0;
+
+ for(int index = startErrorIdx; index <= endErrorIdx; index++){
+ DecodeErrorInfo einfo = sourceError.get(index);
+ int pos = einfo.getCharPosition();
+ if(pos < startPos) continue;
+ if(pos >= endPos) break;
+ DecodeErrorInfo newInfo = einfo.createGappedClone(gap);
+ if(result == null){
+ result = createErrorList();
+ }
+ result.add(newInfo);
+ }
+
+ return result;
+ }
+
+ /**
+ * エラー格納用リストを生成する。
+ * @return リスト
+ */
+ private static List<DecodeErrorInfo> createErrorList(){
+ List<DecodeErrorInfo> result = new ArrayList<DecodeErrorInfo>();
+ return result;
+ }
+
+ static{
+ assert createErrorList() instanceof RandomAccess;
+ }
+
+ /**
+ * 初期化下請け。
+ * 長さ0の文字列&デコードエラー無しの状態になる。
+ */
+ private void initImpl(){
+ this.rawContent.setLength(0);
+
+ if(this.decodeError != null){
+ this.decodeError.clear();
+ }
+
+ return;
+ }
+
+ /**
+ * 事前にキャパシティを確保する。
+ * 指定されたキャパシティの範囲内で再割り当てが起きないことを保証する。
+ * @param minimumCapacity キャラクタ単位のキャパシティ長。
+ */
+ public void ensureCapacity(int minimumCapacity){
+ this.rawContent.ensureCapacity(minimumCapacity);
+ return;
+ }
+
+ /**
+ * 初期化。
+ * 長さ0の文字列&デコードエラー無しの状態になる。
+ * コンストラクタで新インスタンスを作るより低コスト。
+ */
+ public void init(){
+ initImpl();
+ return;
+ }
+
+ /**
+ * デコードエラーを含むか判定する。
+ * @return デコードエラーを含むならtrue
+ */
+ public boolean hasDecodeError(){
+ if(this.decodeError == null) return false;
+ if(this.decodeError.isEmpty()) return false;
+ return true;
+ }
+
+ /**
+ * デコードエラーの一覧を取得する。
+ * @return デコードエラーの一覧
+ */
+ public List<DecodeErrorInfo> getDecodeErrorList(){
+ if( ! hasDecodeError() ){
+ return EMPTY_LIST;
+ }
+ return Collections.unmodifiableList(this.decodeError);
+ }
+
+ /**
+ * 生の文字列を得る。
+ * 高速なCharSequenceアクセス用途。
+ * @return 生の文字列。
+ */
+ public CharSequence getRawContent(){
+ return this.rawContent;
+ }
+
+ /**
+ * 指定された位置の文字を変更する。
+ * @param index 文字位置
+ * @param ch 文字
+ * @throws IndexOutOfBoundsException 不正な位置指定
+ */
+ public void setCharAt(int index, char ch)
+ throws IndexOutOfBoundsException{
+ this.rawContent.setCharAt(index, ch);
+ return;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @param index {@inheritDoc}
+ * @return {@inheritDoc}
+ */
+ @Override
+ public char charAt(int index){
+ return this.rawContent.charAt(index);
+ }
+
+ /**
+ * {@inheritDoc}
+ * @return {@inheritDoc}
+ */
+ @Override
+ public int length(){
+ return this.rawContent.length();
+ }
+
+ /**
+ * {@inheritDoc}
+ * @param start {@inheritDoc}
+ * @param end {@inheritDoc}
+ * @return {@inheritDoc}
+ */
+ @Override
+ public CharSequence subSequence(int start, int end){
+ return this.rawContent.subSequence(start, end);
+ }
+
+ /**
+ * 範囲指定されたサブコンテントを切り出す。
+ * サブコンテントにはデコードエラー情報が引き継がれる。
+ * @param start 開始位置
+ * @param end 終了位置
+ * @return サブコンテント
+ * @throws IndexOutOfBoundsException start または end が負の値の場合、
+ * end が length() より大きい場合、あるいは start が end より大きい場合
+ */
+ public DecodedContent subContent(int start, int end)
+ throws IndexOutOfBoundsException{
+ int length = end - start;
+ if(length < 0) throw new IndexOutOfBoundsException();
+ DecodedContent result = new DecodedContent(length);
+ result.append(this, start, end);
+ return result;
+ }
+
+ /**
+ * 文字を追加する。
+ * @param letter 追加する文字
+ * @return thisオブジェクト
+ */
+ public DecodedContent append(char letter){
+ this.rawContent.append(letter);
+ return this;
+ }
+
+ /**
+ * 文字列を追加する。
+ * @param seq 追加する文字列
+ * @return thisオブジェクト
+ */
+ public DecodedContent append(CharSequence seq){
+ if(seq == null){
+ this.rawContent.append(NULLTEXT);
+ }else if(seq instanceof DecodedContent){
+ append((DecodedContent)seq, 0, seq.length());
+ }else{
+ this.rawContent.append(seq);
+ }
+ return this;
+ }
+
+ /**
+ * 文字列を追加する。
+ * @param seq 追加する文字列
+ * @param startPos 開始位置
+ * @param endPos 終了位置
+ * @return thisオブジェクト
+ * @throws IndexOutOfBoundsException 範囲指定が変。
+ */
+ public DecodedContent append(CharSequence seq,
+ int startPos, int endPos)
+ throws IndexOutOfBoundsException{
+ if(seq == null){
+ this.rawContent.append(NULLTEXT, startPos, endPos);
+ }else if(seq instanceof DecodedContent){
+ append((DecodedContent)seq, startPos, endPos);
+ }else{
+ this.rawContent.append(seq, startPos, endPos);
+ }
+
+ return this;
+ }
+
+ /**
+ * 文字列を追加する。
+ * @param source 追加する文字列
+ * @param startPos 開始位置
+ * @param endPos 終了位置
+ * @return thisオブジェクト
+ * @throws IndexOutOfBoundsException 範囲指定が変。
+ */
+ public DecodedContent append(DecodedContent source,
+ int startPos, int endPos)
+ throws IndexOutOfBoundsException{
+ if(source == null){
+ return append(NULLTEXT, startPos, endPos);
+ }
+
+ int gap = startPos - this.rawContent.length();
+
+ this.rawContent.append(source.rawContent, startPos, endPos);
+
+ if( ! source.hasDecodeError() ) return this;
+
+ List<DecodeErrorInfo> targetErrorList;
+ if(source != this) targetErrorList = this.decodeError;
+ else targetErrorList = null;
+
+ targetErrorList = appendGappedErrorInfo(source,
+ startPos, endPos,
+ targetErrorList,
+ gap);
+
+ if(targetErrorList == null) return this;
+ if(targetErrorList == this.decodeError) return this;
+
+ if(this.decodeError == null){
+ this.decodeError = targetErrorList;
+ }else{
+ this.decodeError.addAll(targetErrorList);
+ }
+
+ return this;
+ }
+
+ /**
+ * 代替文字とともにデコードエラーを追加する。
+ * ※呼び出し側は、追加されるデコードエラーの位置情報が
+ * 既存のデコードエラーよりも大きいことを保証しなければならない。
+ * @param errorInfo デコードエラー
+ */
+ private void addDecodeError(DecodeErrorInfo errorInfo){
+ if(this.decodeError == null){
+ this.decodeError = createErrorList();
+ }
+ this.decodeError.add(errorInfo);
+ this.rawContent.append(ALTCHAR);
+ return;
+ }
+
+ /**
+ * 代替文字とともにデコードエラーを追加する。
+ * @param b1st 1バイト目の値
+ */
+ public void addDecodeError(byte b1st){
+ DecodeErrorInfo errInfo =
+ new DecodeErrorInfo(this.rawContent.length(), b1st);
+ addDecodeError(errInfo);
+ return;
+ }
+
+ /**
+ * 代替文字とともにデコードエラーを追加する。
+ * @param b1st 1バイト目の値
+ * @param b2nd 2バイト目の値
+ */
+ public void addDecodeError(byte b1st, byte b2nd){
+ DecodeErrorInfo errInfo =
+ new DecodeErrorInfo(this.rawContent.length(), b1st, b2nd);
+ addDecodeError(errInfo);
+ return;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @return {@inheritDoc}
+ */
+ @Override
+ public String toString(){
+ return this.rawContent.toString();
+ }
+
+}
-/*\r
- * entity converter\r
- *\r
- * License : The MIT License\r
- * Copyright(c) 2009 olyutorskii\r
- */\r
-\r
-package jp.sourceforge.jindolf.parser;\r
-\r
-import java.util.regex.Matcher;\r
-import java.util.regex.Pattern;\r
-\r
-/**\r
- * 人狼BBSで用いられる4種類のXHTML文字実体参照の\r
- * 解決を伴う{@link DecodedContent}の切り出しを行う。\r
- * 文字実体参照は{@code > < " &}が対象。\r
- * U+005C(バックスラッシュ)をU+00A5(円通貨)に直す処理も行われる。\r
- * ※ 人狼BBSはShift_JIS(⊃JISX0201)で運営されているので、\r
- * バックスラッシュは登場しないはず。\r
- * ※ が、バックスラッシュを生成するShift_JISデコーダは存在する。\r
- * マルチスレッドには非対応。\r
- */\r
-public class EntityConverter{\r
-\r
- private static final String[][] XCHG_TABLE = {\r
- {">", ">"},\r
- {"<", "<"},\r
- {""", "\""},\r
- {"&", "&"},\r
- {"\u005c\u005c", "\u00a5"},\r
- };\r
-\r
- private static final Pattern XCHG_PATTERN;\r
-\r
- static{\r
- StringBuilder regex = new StringBuilder();\r
- for(String[] xchg : XCHG_TABLE){\r
- String xchgFrom = xchg[0];\r
- if(regex.length() > 0) regex.append('|');\r
- regex.append('(')\r
- .append(Pattern.quote(xchgFrom))\r
- .append(')');\r
- assert xchgFrom.indexOf(DecodedContent.ALTCHAR) < 0;\r
- }\r
- XCHG_PATTERN = Pattern.compile(regex.toString());\r
- }\r
-\r
- private final Matcher matcher = XCHG_PATTERN.matcher("");\r
-\r
- /**\r
- * コンストラクタ。\r
- */\r
- public EntityConverter(){\r
- super();\r
- return;\r
- }\r
-\r
- /**\r
- * 実体参照の変換を行う。\r
- * @param content 変換元文書\r
- * @return 切り出された変換済み文書\r
- */\r
- public DecodedContent convert(DecodedContent content){\r
- return append(null, content, 0, content.length());\r
- }\r
-\r
- /**\r
- * 実体参照の変換を行う。\r
- * @param content 変換元文書\r
- * @param range 範囲指定\r
- * @return 切り出された変換済み文書\r
- * @throws IndexOutOfBoundsException 位置指定に不正があった\r
- */\r
- public DecodedContent convert(DecodedContent content, SeqRange range)\r
- throws IndexOutOfBoundsException{\r
- return append(null, content, range.getStartPos(), range.getEndPos());\r
- }\r
-\r
- /**\r
- * 実体参照の変換を行う。\r
- * @param content 変換元文書\r
- * @param startPos 開始位置\r
- * @param endPos 終了位置\r
- * @return 切り出された変換済み文書\r
- * @throws IndexOutOfBoundsException 位置指定に不正があった\r
- */\r
- public DecodedContent convert(DecodedContent content,\r
- int startPos, int endPos)\r
- throws IndexOutOfBoundsException{\r
- return append(null, content, startPos, endPos);\r
- }\r
-\r
- /**\r
- * 実体参照の変換を行い既存のDecodedContentに追加を行う。\r
- * @param target 追加先文書。nullなら新たな文書が用意される。\r
- * @param content 変換元文書\r
- * @return targetもしくは新規に用意された文書\r
- * @throws IndexOutOfBoundsException 位置指定に不正があった\r
- */\r
- public DecodedContent append(DecodedContent target,\r
- DecodedContent content)\r
- throws IndexOutOfBoundsException{\r
- return append(target, content, 0, content.length());\r
- }\r
-\r
- /**\r
- * 実体参照の変換を行い既存のDecodedContentに追加を行う。\r
- * @param target 追加先文書。nullなら新たな文書が用意される。\r
- * @param content 変換元文書\r
- * @param range 範囲指定\r
- * @return targetもしくは新規に用意された文書\r
- * @throws IndexOutOfBoundsException 位置指定に不正があった\r
- */\r
- public DecodedContent append(DecodedContent target,\r
- DecodedContent content,\r
- SeqRange range )\r
- throws IndexOutOfBoundsException{\r
- return append(target, content,\r
- range.getStartPos(), range.getEndPos());\r
- }\r
-\r
- /**\r
- * 実体参照の変換を行い既存のDecodedContentに追加を行う。\r
- * @param target 追加先文書。nullなら新たな文書が用意される。\r
- * @param content 変換元文書\r
- * @param startPos 開始位置\r
- * @param endPos 終了位置\r
- * @return targetもしくは新規に用意された文書\r
- * @throws IndexOutOfBoundsException 位置指定に不正があった\r
- */\r
- public DecodedContent append(DecodedContent target,\r
- DecodedContent content,\r
- int startPos, int endPos)\r
- throws IndexOutOfBoundsException{\r
- if( startPos > endPos\r
- || startPos < 0\r
- || content.length() < endPos){\r
- throw new IndexOutOfBoundsException();\r
- }\r
-\r
- DecodedContent result;\r
- if(target == null){\r
- result = new DecodedContent(endPos - startPos);\r
- }else{\r
- result = target;\r
- }\r
-\r
- this.matcher.reset(content.getRawContent());\r
- this.matcher.region(startPos, endPos);\r
-\r
- int lastPos = startPos;\r
- while(this.matcher.find()){\r
- int group;\r
- int matchStart = -1;\r
- for(group = 1; group <= XCHG_TABLE.length; group++){\r
- matchStart = this.matcher.start(group);\r
- if(matchStart >= 0) break;\r
- }\r
- int matchEnd = this.matcher.end(group);\r
-\r
- result.append(content, lastPos, matchStart);\r
-\r
- String toStr = XCHG_TABLE[group - 1][1];\r
- result.append(toStr);\r
-\r
- lastPos = matchEnd;\r
- }\r
- result.append(content, lastPos, endPos);\r
-\r
- this.matcher.reset("");\r
-\r
- return result;\r
- }\r
-\r
-}\r
+/*
+ * entity converter
+ *
+ * License : The MIT License
+ * Copyright(c) 2009 olyutorskii
+ */
+
+package jp.sourceforge.jindolf.parser;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * 人狼BBSで用いられる4種類のXHTML文字実体参照の
+ * 解決を伴う{@link DecodedContent}の切り出しを行う。
+ * 文字実体参照は{@code > < " &}が対象。
+ * U+005C(バックスラッシュ)をU+00A5(円通貨)に直す処理も行われる。
+ * ※ 人狼BBSはShift_JIS(⊃JISX0201)で運営されているので、
+ * バックスラッシュは登場しないはず。
+ * ※ が、バックスラッシュを生成するShift_JISデコーダは存在する。
+ * マルチスレッドには非対応。
+ */
+public class EntityConverter{
+
+ private static final String[][] XCHG_TABLE = {
+ {">", ">"},
+ {"<", "<"},
+ {""", "\""},
+ {"&", "&"},
+ {"\u005c\u005c", "\u00a5"},
+ };
+
+ private static final Pattern XCHG_PATTERN;
+
+ static{
+ StringBuilder regex = new StringBuilder();
+ for(String[] xchg : XCHG_TABLE){
+ String xchgFrom = xchg[0];
+ if(regex.length() > 0) regex.append('|');
+ regex.append('(')
+ .append(Pattern.quote(xchgFrom))
+ .append(')');
+ assert xchgFrom.indexOf(DecodedContent.ALTCHAR) < 0;
+ }
+ XCHG_PATTERN = Pattern.compile(regex.toString());
+ }
+
+ private final Matcher matcher = XCHG_PATTERN.matcher("");
+
+ /**
+ * コンストラクタ。
+ */
+ public EntityConverter(){
+ super();
+ return;
+ }
+
+ /**
+ * 実体参照の変換を行う。
+ * @param content 変換元文書
+ * @return 切り出された変換済み文書
+ */
+ public DecodedContent convert(DecodedContent content){
+ return append(null, content, 0, content.length());
+ }
+
+ /**
+ * 実体参照の変換を行う。
+ * @param content 変換元文書
+ * @param range 範囲指定
+ * @return 切り出された変換済み文書
+ * @throws IndexOutOfBoundsException 位置指定に不正があった
+ */
+ public DecodedContent convert(DecodedContent content, SeqRange range)
+ throws IndexOutOfBoundsException{
+ return append(null, content, range.getStartPos(), range.getEndPos());
+ }
+
+ /**
+ * 実体参照の変換を行う。
+ * @param content 変換元文書
+ * @param startPos 開始位置
+ * @param endPos 終了位置
+ * @return 切り出された変換済み文書
+ * @throws IndexOutOfBoundsException 位置指定に不正があった
+ */
+ public DecodedContent convert(DecodedContent content,
+ int startPos, int endPos)
+ throws IndexOutOfBoundsException{
+ return append(null, content, startPos, endPos);
+ }
+
+ /**
+ * 実体参照の変換を行い既存のDecodedContentに追加を行う。
+ * @param target 追加先文書。nullなら新たな文書が用意される。
+ * @param content 変換元文書
+ * @return targetもしくは新規に用意された文書
+ * @throws IndexOutOfBoundsException 位置指定に不正があった
+ */
+ public DecodedContent append(DecodedContent target,
+ DecodedContent content)
+ throws IndexOutOfBoundsException{
+ return append(target, content, 0, content.length());
+ }
+
+ /**
+ * 実体参照の変換を行い既存のDecodedContentに追加を行う。
+ * @param target 追加先文書。nullなら新たな文書が用意される。
+ * @param content 変換元文書
+ * @param range 範囲指定
+ * @return targetもしくは新規に用意された文書
+ * @throws IndexOutOfBoundsException 位置指定に不正があった
+ */
+ public DecodedContent append(DecodedContent target,
+ DecodedContent content,
+ SeqRange range )
+ throws IndexOutOfBoundsException{
+ return append(target, content,
+ range.getStartPos(), range.getEndPos());
+ }
+
+ /**
+ * 実体参照の変換を行い既存のDecodedContentに追加を行う。
+ * @param target 追加先文書。nullなら新たな文書が用意される。
+ * @param content 変換元文書
+ * @param startPos 開始位置
+ * @param endPos 終了位置
+ * @return targetもしくは新規に用意された文書
+ * @throws IndexOutOfBoundsException 位置指定に不正があった
+ */
+ public DecodedContent append(DecodedContent target,
+ DecodedContent content,
+ int startPos, int endPos)
+ throws IndexOutOfBoundsException{
+ if( startPos > endPos
+ || startPos < 0
+ || content.length() < endPos){
+ throw new IndexOutOfBoundsException();
+ }
+
+ DecodedContent result;
+ if(target == null){
+ result = new DecodedContent(endPos - startPos);
+ }else{
+ result = target;
+ }
+
+ this.matcher.reset(content.getRawContent());
+ this.matcher.region(startPos, endPos);
+
+ int lastPos = startPos;
+ while(this.matcher.find()){
+ int group;
+ int matchStart = -1;
+ for(group = 1; group <= XCHG_TABLE.length; group++){
+ matchStart = this.matcher.start(group);
+ if(matchStart >= 0) break;
+ }
+ int matchEnd = this.matcher.end(group);
+
+ result.append(content, lastPos, matchStart);
+
+ String toStr = XCHG_TABLE[group - 1][1];
+ result.append(toStr);
+
+ lastPos = matchEnd;
+ }
+ result.append(content, lastPos, endPos);
+
+ this.matcher.reset("");
+
+ return result;
+ }
+
+}
-/*\r
- * html handler adapter\r
- *\r
- * License : The MIT License\r
- * Copyright(c) 2009 olyutorskii\r
- */\r
-\r
-package jp.sourceforge.jindolf.parser;\r
-\r
-import jp.sourceforge.jindolf.corelib.EventFamily;\r
-import jp.sourceforge.jindolf.corelib.GameRole;\r
-import jp.sourceforge.jindolf.corelib.PeriodType;\r
-import jp.sourceforge.jindolf.corelib.SysEventType;\r
-import jp.sourceforge.jindolf.corelib.TalkType;\r
-import jp.sourceforge.jindolf.corelib.Team;\r
-import jp.sourceforge.jindolf.corelib.VillageState;\r
-\r
-/**\r
- * インタフェース{@link HtmlHandler}の抽象アダプタクラス。\r
- * このクラスのメソッド自身は何もしない。\r
- */\r
-public abstract class HtmlAdapter implements HtmlHandler{\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @param content {@inheritDoc}\r
- * @throws HtmlParseException {@inheritDoc}\r
- */\r
- @Override\r
- public void startParse(DecodedContent content)\r
- throws HtmlParseException{\r
- return;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @param content {@inheritDoc}\r
- * @param titleRange {@inheritDoc}\r
- * @throws HtmlParseException {@inheritDoc}\r
- */\r
- @Override\r
- public void pageTitle(DecodedContent content, SeqRange titleRange)\r
- throws HtmlParseException{\r
- return;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @param content {@inheritDoc}\r
- * @param loginRange {@inheritDoc}\r
- * @throws HtmlParseException {@inheritDoc}\r
- */\r
- @Override\r
- public void loginName(DecodedContent content, SeqRange loginRange)\r
- throws HtmlParseException{\r
- return;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @param type {@inheritDoc}\r
- * @throws HtmlParseException {@inheritDoc}\r
- */\r
- @Override\r
- public void pageType(PageType type)\r
- throws HtmlParseException{\r
- return;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @param content {@inheritDoc}\r
- * @param villageRange {@inheritDoc}\r
- * @throws HtmlParseException {@inheritDoc}\r
- */\r
- @Override\r
- public void villageName(DecodedContent content, SeqRange villageRange)\r
- throws HtmlParseException{\r
- return;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @param month {@inheritDoc}\r
- * @param day {@inheritDoc}\r
- * @param hour {@inheritDoc}\r
- * @param minute {@inheritDoc}\r
- * @throws HtmlParseException {@inheritDoc}\r
- */\r
- @Override\r
- public void commitTime(int month, int day, int hour, int minute)\r
- throws HtmlParseException{\r
- return;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @param content {@inheritDoc}\r
- * @param anchorRange {@inheritDoc}\r
- * @param periodType {@inheritDoc}\r
- * @param day {@inheritDoc}\r
- * @throws HtmlParseException {@inheritDoc}\r
- */\r
- @Override\r
- public void periodLink(DecodedContent content,\r
- SeqRange anchorRange,\r
- PeriodType periodType, int day)\r
- throws HtmlParseException{\r
- return;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @param content {@inheritDoc}\r
- * @param anchorRange {@inheritDoc}\r
- * @param villageRange {@inheritDoc}\r
- * @param hour {@inheritDoc}\r
- * @param minute {@inheritDoc}\r
- * @param state {@inheritDoc}\r
- * @throws HtmlParseException {@inheritDoc}\r
- */\r
- @Override\r
- public void villageRecord(DecodedContent content,\r
- SeqRange anchorRange,\r
- SeqRange villageRange,\r
- int hour, int minute,\r
- VillageState state )\r
- throws HtmlParseException{\r
- return;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @throws HtmlParseException {@inheritDoc}\r
- */\r
- @Override\r
- public void endParse() throws HtmlParseException{\r
- return;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @throws HtmlParseException {@inheritDoc}\r
- */\r
- @Override\r
- public void startTalk() throws HtmlParseException{\r
- return;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @throws HtmlParseException {@inheritDoc}\r
- */\r
- @Override\r
- public void endTalk() throws HtmlParseException{\r
- return;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @param talkNo {@inheritDoc}\r
- * @throws HtmlParseException {@inheritDoc}\r
- */\r
- @Override\r
- public void talkNo(int talkNo) throws HtmlParseException{\r
- return;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @param content {@inheritDoc}\r
- * @param idRange {@inheritDoc}\r
- * @throws HtmlParseException {@inheritDoc}\r
- */\r
- @Override\r
- public void talkId(DecodedContent content, SeqRange idRange)\r
- throws HtmlParseException{\r
- return;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @param content {@inheritDoc}\r
- * @param avatarRange {@inheritDoc}\r
- * @throws HtmlParseException {@inheritDoc}\r
- */\r
- @Override\r
- public void talkAvatar(DecodedContent content, SeqRange avatarRange)\r
- throws HtmlParseException{\r
- return;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @param hour {@inheritDoc}\r
- * @param minute {@inheritDoc}\r
- * @throws HtmlParseException {@inheritDoc}\r
- */\r
- @Override\r
- public void talkTime(int hour, int minute) throws HtmlParseException{\r
- return;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @param content {@inheritDoc}\r
- * @param urlRange {@inheritDoc}\r
- * @throws HtmlParseException {@inheritDoc}\r
- */\r
- @Override\r
- public void talkIconUrl(DecodedContent content, SeqRange urlRange)\r
- throws HtmlParseException{\r
- return;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @param type {@inheritDoc}\r
- * @throws HtmlParseException {@inheritDoc}\r
- */\r
- @Override\r
- public void talkType(TalkType type) throws HtmlParseException{\r
- return;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @param content {@inheritDoc}\r
- * @param textRange {@inheritDoc}\r
- * @throws HtmlParseException {@inheritDoc}\r
- */\r
- @Override\r
- public void talkText(DecodedContent content, SeqRange textRange)\r
- throws HtmlParseException{\r
- return;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @throws HtmlParseException {@inheritDoc}\r
- */\r
- @Override\r
- public void talkBreak() throws HtmlParseException{\r
- return;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @param eventFamily {@inheritDoc}\r
- * @throws HtmlParseException {@inheritDoc}\r
- */\r
- @Override\r
- public void startSysEvent(EventFamily eventFamily)\r
- throws HtmlParseException{\r
- return;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @param type {@inheritDoc}\r
- * @throws HtmlParseException {@inheritDoc}\r
- */\r
- @Override\r
- public void sysEventType(SysEventType type) throws HtmlParseException{\r
- return;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @throws HtmlParseException {@inheritDoc}\r
- */\r
- @Override\r
- public void endSysEvent() throws HtmlParseException{\r
- return;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @param content {@inheritDoc}\r
- * @param entryNo {@inheritDoc}\r
- * @param avatarRange {@inheritDoc}\r
- * @throws HtmlParseException {@inheritDoc}\r
- */\r
- @Override\r
- public void sysEventOnStage(DecodedContent content,\r
- int entryNo,\r
- SeqRange avatarRange )\r
- throws HtmlParseException{\r
- return;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @param role {@inheritDoc}\r
- * @param num {@inheritDoc}\r
- * @throws HtmlParseException {@inheritDoc}\r
- */\r
- @Override\r
- public void sysEventOpenRole(GameRole role, int num)\r
- throws HtmlParseException{\r
- return;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @param content {@inheritDoc}\r
- * @param avatarRange {@inheritDoc}\r
- * @throws HtmlParseException {@inheritDoc}\r
- */\r
- @Override\r
- public void sysEventSurvivor(DecodedContent content,\r
- SeqRange avatarRange)\r
- throws HtmlParseException{\r
- return;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @param content {@inheritDoc}\r
- * @param voteByRange {@inheritDoc}\r
- * @param voteToRange {@inheritDoc}\r
- * @throws HtmlParseException {@inheritDoc}\r
- */\r
- @Override\r
- public void sysEventCounting(DecodedContent content,\r
- SeqRange voteByRange,\r
- SeqRange voteToRange )\r
- throws HtmlParseException{\r
- return;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @param content {@inheritDoc}\r
- * @param voteByRange {@inheritDoc}\r
- * @param voteToRange {@inheritDoc}\r
- * @throws HtmlParseException {@inheritDoc}\r
- */\r
- @Override\r
- public void sysEventCounting2(DecodedContent content,\r
- SeqRange voteByRange,\r
- SeqRange voteToRange )\r
- throws HtmlParseException{\r
- return;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @param content {@inheritDoc}\r
- * @param avatarRange {@inheritDoc}\r
- * @throws HtmlParseException {@inheritDoc}\r
- */\r
- @Override\r
- public void sysEventSuddenDeath(DecodedContent content,\r
- SeqRange avatarRange )\r
- throws HtmlParseException{\r
- return;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @param content {@inheritDoc}\r
- * @param avatarRange {@inheritDoc}\r
- * @throws HtmlParseException {@inheritDoc}\r
- */\r
- @Override\r
- public void sysEventMurdered(DecodedContent content,\r
- SeqRange avatarRange )\r
- throws HtmlParseException{\r
- return;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @param content {@inheritDoc}\r
- * @param avatarRange {@inheritDoc}\r
- * @param anchorRange {@inheritDoc}\r
- * @param loginRange {@inheritDoc}\r
- * @param isLiving {@inheritDoc}\r
- * @param role {@inheritDoc}\r
- * @throws HtmlParseException {@inheritDoc}\r
- */\r
- @Override\r
- public void sysEventPlayerList(DecodedContent content,\r
- SeqRange avatarRange,\r
- SeqRange anchorRange,\r
- SeqRange loginRange,\r
- boolean isLiving,\r
- GameRole role)\r
- throws HtmlParseException{\r
- return;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @param content {@inheritDoc}\r
- * @param avatarRange {@inheritDoc}\r
- * @param votes {@inheritDoc}\r
- * @throws HtmlParseException {@inheritDoc}\r
- */\r
- @Override\r
- public void sysEventExecution(DecodedContent content,\r
- SeqRange avatarRange,\r
- int votes )\r
- throws HtmlParseException{\r
- return;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @param content {@inheritDoc}\r
- * @param avatarRange {@inheritDoc}\r
- * @throws HtmlParseException {@inheritDoc}\r
- */\r
- @Override\r
- public void sysEventVanish(DecodedContent content,\r
- SeqRange avatarRange )\r
- throws HtmlParseException{\r
- return;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @param content {@inheritDoc}\r
- * @param avatarRange {@inheritDoc}\r
- * @throws HtmlParseException {@inheritDoc}\r
- */\r
- @Override\r
- public void sysEventCheckout(DecodedContent content,\r
- SeqRange avatarRange )\r
- throws HtmlParseException{\r
- return;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @param content {@inheritDoc}\r
- * @param judgeByRange {@inheritDoc}\r
- * @param judgeToRange {@inheritDoc}\r
- * @throws HtmlParseException {@inheritDoc}\r
- */\r
- @Override\r
- public void sysEventJudge(DecodedContent content,\r
- SeqRange judgeByRange,\r
- SeqRange judgeToRange )\r
- throws HtmlParseException{\r
- return;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @param content {@inheritDoc}\r
- * @param guardByRange {@inheritDoc}\r
- * @param guardToRange {@inheritDoc}\r
- * @throws HtmlParseException {@inheritDoc}\r
- */\r
- @Override\r
- public void sysEventGuard(DecodedContent content,\r
- SeqRange guardByRange,\r
- SeqRange guardToRange )\r
- throws HtmlParseException{\r
- return;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @param hour {@inheritDoc}\r
- * @param minute {@inheritDoc}\r
- * @param minLimit {@inheritDoc}\r
- * @param maxLimit {@inheritDoc}\r
- * @throws HtmlParseException {@inheritDoc}\r
- */\r
- @Override\r
- public void sysEventAskEntry(int hour, int minute,\r
- int minLimit, int maxLimit)\r
- throws HtmlParseException{\r
- return;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @param hour {@inheritDoc}\r
- * @param minute {@inheritDoc}\r
- * @throws HtmlParseException {@inheritDoc}\r
- */\r
- @Override\r
- public void sysEventAskCommit(int hour, int minute)\r
- throws HtmlParseException{\r
- return;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @param content {@inheritDoc}\r
- * @param avatarRange {@inheritDoc}\r
- * @throws HtmlParseException {@inheritDoc}\r
- */\r
- @Override\r
- public void sysEventNoComment(DecodedContent content,\r
- SeqRange avatarRange )\r
- throws HtmlParseException{\r
- return;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @param winner {@inheritDoc}\r
- * @param hour {@inheritDoc}\r
- * @param minute {@inheritDoc}\r
- * @throws HtmlParseException {@inheritDoc}\r
- */\r
- @Override\r
- public void sysEventStayEpilogue(Team winner, int hour, int minute)\r
- throws HtmlParseException{\r
- return;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @param content {@inheritDoc}\r
- * @param contentRange {@inheritDoc}\r
- * @throws HtmlParseException {@inheritDoc}\r
- */\r
- @Override\r
- public void sysEventContent(DecodedContent content,\r
- SeqRange contentRange )\r
- throws HtmlParseException{\r
- return;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @throws HtmlParseException {@inheritDoc}\r
- */\r
- @Override\r
- public void sysEventContentBreak() throws HtmlParseException{\r
- return;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @param content {@inheritDoc}\r
- * @param anchorRange {@inheritDoc}\r
- * @param contentRange {@inheritDoc}\r
- * @throws HtmlParseException {@inheritDoc}\r
- */\r
- @Override\r
- public void sysEventContentAnchor(DecodedContent content,\r
- SeqRange anchorRange,\r
- SeqRange contentRange )\r
- throws HtmlParseException{\r
- return;\r
- }\r
-\r
-}\r
+/*
+ * html handler adapter
+ *
+ * License : The MIT License
+ * Copyright(c) 2009 olyutorskii
+ */
+
+package jp.sourceforge.jindolf.parser;
+
+import jp.sourceforge.jindolf.corelib.EventFamily;
+import jp.sourceforge.jindolf.corelib.GameRole;
+import jp.sourceforge.jindolf.corelib.PeriodType;
+import jp.sourceforge.jindolf.corelib.SysEventType;
+import jp.sourceforge.jindolf.corelib.TalkType;
+import jp.sourceforge.jindolf.corelib.Team;
+import jp.sourceforge.jindolf.corelib.VillageState;
+
+/**
+ * インタフェース{@link HtmlHandler}の抽象アダプタクラス。
+ * このクラスのメソッド自身は何もしない。
+ */
+public abstract class HtmlAdapter implements HtmlHandler{
+
+ /**
+ * {@inheritDoc}
+ * @param content {@inheritDoc}
+ * @throws HtmlParseException {@inheritDoc}
+ */
+ @Override
+ public void startParse(DecodedContent content)
+ throws HtmlParseException{
+ return;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @param content {@inheritDoc}
+ * @param titleRange {@inheritDoc}
+ * @throws HtmlParseException {@inheritDoc}
+ */
+ @Override
+ public void pageTitle(DecodedContent content, SeqRange titleRange)
+ throws HtmlParseException{
+ return;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @param content {@inheritDoc}
+ * @param loginRange {@inheritDoc}
+ * @throws HtmlParseException {@inheritDoc}
+ */
+ @Override
+ public void loginName(DecodedContent content, SeqRange loginRange)
+ throws HtmlParseException{
+ return;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @param type {@inheritDoc}
+ * @throws HtmlParseException {@inheritDoc}
+ */
+ @Override
+ public void pageType(PageType type)
+ throws HtmlParseException{
+ return;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @param content {@inheritDoc}
+ * @param villageRange {@inheritDoc}
+ * @throws HtmlParseException {@inheritDoc}
+ */
+ @Override
+ public void villageName(DecodedContent content, SeqRange villageRange)
+ throws HtmlParseException{
+ return;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @param month {@inheritDoc}
+ * @param day {@inheritDoc}
+ * @param hour {@inheritDoc}
+ * @param minute {@inheritDoc}
+ * @throws HtmlParseException {@inheritDoc}
+ */
+ @Override
+ public void commitTime(int month, int day, int hour, int minute)
+ throws HtmlParseException{
+ return;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @param content {@inheritDoc}
+ * @param anchorRange {@inheritDoc}
+ * @param periodType {@inheritDoc}
+ * @param day {@inheritDoc}
+ * @throws HtmlParseException {@inheritDoc}
+ */
+ @Override
+ public void periodLink(DecodedContent content,
+ SeqRange anchorRange,
+ PeriodType periodType, int day)
+ throws HtmlParseException{
+ return;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @param content {@inheritDoc}
+ * @param anchorRange {@inheritDoc}
+ * @param villageRange {@inheritDoc}
+ * @param hour {@inheritDoc}
+ * @param minute {@inheritDoc}
+ * @param state {@inheritDoc}
+ * @throws HtmlParseException {@inheritDoc}
+ */
+ @Override
+ public void villageRecord(DecodedContent content,
+ SeqRange anchorRange,
+ SeqRange villageRange,
+ int hour, int minute,
+ VillageState state )
+ throws HtmlParseException{
+ return;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @throws HtmlParseException {@inheritDoc}
+ */
+ @Override
+ public void endParse() throws HtmlParseException{
+ return;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @throws HtmlParseException {@inheritDoc}
+ */
+ @Override
+ public void startTalk() throws HtmlParseException{
+ return;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @throws HtmlParseException {@inheritDoc}
+ */
+ @Override
+ public void endTalk() throws HtmlParseException{
+ return;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @param talkNo {@inheritDoc}
+ * @throws HtmlParseException {@inheritDoc}
+ */
+ @Override
+ public void talkNo(int talkNo) throws HtmlParseException{
+ return;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @param content {@inheritDoc}
+ * @param idRange {@inheritDoc}
+ * @throws HtmlParseException {@inheritDoc}
+ */
+ @Override
+ public void talkId(DecodedContent content, SeqRange idRange)
+ throws HtmlParseException{
+ return;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @param content {@inheritDoc}
+ * @param avatarRange {@inheritDoc}
+ * @throws HtmlParseException {@inheritDoc}
+ */
+ @Override
+ public void talkAvatar(DecodedContent content, SeqRange avatarRange)
+ throws HtmlParseException{
+ return;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @param hour {@inheritDoc}
+ * @param minute {@inheritDoc}
+ * @throws HtmlParseException {@inheritDoc}
+ */
+ @Override
+ public void talkTime(int hour, int minute) throws HtmlParseException{
+ return;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @param content {@inheritDoc}
+ * @param urlRange {@inheritDoc}
+ * @throws HtmlParseException {@inheritDoc}
+ */
+ @Override
+ public void talkIconUrl(DecodedContent content, SeqRange urlRange)
+ throws HtmlParseException{
+ return;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @param type {@inheritDoc}
+ * @throws HtmlParseException {@inheritDoc}
+ */
+ @Override
+ public void talkType(TalkType type) throws HtmlParseException{
+ return;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @param content {@inheritDoc}
+ * @param textRange {@inheritDoc}
+ * @throws HtmlParseException {@inheritDoc}
+ */
+ @Override
+ public void talkText(DecodedContent content, SeqRange textRange)
+ throws HtmlParseException{
+ return;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @throws HtmlParseException {@inheritDoc}
+ */
+ @Override
+ public void talkBreak() throws HtmlParseException{
+ return;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @param eventFamily {@inheritDoc}
+ * @throws HtmlParseException {@inheritDoc}
+ */
+ @Override
+ public void startSysEvent(EventFamily eventFamily)
+ throws HtmlParseException{
+ return;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @param type {@inheritDoc}
+ * @throws HtmlParseException {@inheritDoc}
+ */
+ @Override
+ public void sysEventType(SysEventType type) throws HtmlParseException{
+ return;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @throws HtmlParseException {@inheritDoc}
+ */
+ @Override
+ public void endSysEvent() throws HtmlParseException{
+ return;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @param content {@inheritDoc}
+ * @param entryNo {@inheritDoc}
+ * @param avatarRange {@inheritDoc}
+ * @throws HtmlParseException {@inheritDoc}
+ */
+ @Override
+ public void sysEventOnStage(DecodedContent content,
+ int entryNo,
+ SeqRange avatarRange )
+ throws HtmlParseException{
+ return;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @param role {@inheritDoc}
+ * @param num {@inheritDoc}
+ * @throws HtmlParseException {@inheritDoc}
+ */
+ @Override
+ public void sysEventOpenRole(GameRole role, int num)
+ throws HtmlParseException{
+ return;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @param content {@inheritDoc}
+ * @param avatarRange {@inheritDoc}
+ * @throws HtmlParseException {@inheritDoc}
+ */
+ @Override
+ public void sysEventSurvivor(DecodedContent content,
+ SeqRange avatarRange)
+ throws HtmlParseException{
+ return;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @param content {@inheritDoc}
+ * @param voteByRange {@inheritDoc}
+ * @param voteToRange {@inheritDoc}
+ * @throws HtmlParseException {@inheritDoc}
+ */
+ @Override
+ public void sysEventCounting(DecodedContent content,
+ SeqRange voteByRange,
+ SeqRange voteToRange )
+ throws HtmlParseException{
+ return;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @param content {@inheritDoc}
+ * @param voteByRange {@inheritDoc}
+ * @param voteToRange {@inheritDoc}
+ * @throws HtmlParseException {@inheritDoc}
+ */
+ @Override
+ public void sysEventCounting2(DecodedContent content,
+ SeqRange voteByRange,
+ SeqRange voteToRange )
+ throws HtmlParseException{
+ return;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @param content {@inheritDoc}
+ * @param avatarRange {@inheritDoc}
+ * @throws HtmlParseException {@inheritDoc}
+ */
+ @Override
+ public void sysEventSuddenDeath(DecodedContent content,
+ SeqRange avatarRange )
+ throws HtmlParseException{
+ return;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @param content {@inheritDoc}
+ * @param avatarRange {@inheritDoc}
+ * @throws HtmlParseException {@inheritDoc}
+ */
+ @Override
+ public void sysEventMurdered(DecodedContent content,
+ SeqRange avatarRange )
+ throws HtmlParseException{
+ return;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @param content {@inheritDoc}
+ * @param avatarRange {@inheritDoc}
+ * @param anchorRange {@inheritDoc}
+ * @param loginRange {@inheritDoc}
+ * @param isLiving {@inheritDoc}
+ * @param role {@inheritDoc}
+ * @throws HtmlParseException {@inheritDoc}
+ */
+ @Override
+ public void sysEventPlayerList(DecodedContent content,
+ SeqRange avatarRange,
+ SeqRange anchorRange,
+ SeqRange loginRange,
+ boolean isLiving,
+ GameRole role)
+ throws HtmlParseException{
+ return;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @param content {@inheritDoc}
+ * @param avatarRange {@inheritDoc}
+ * @param votes {@inheritDoc}
+ * @throws HtmlParseException {@inheritDoc}
+ */
+ @Override
+ public void sysEventExecution(DecodedContent content,
+ SeqRange avatarRange,
+ int votes )
+ throws HtmlParseException{
+ return;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @param content {@inheritDoc}
+ * @param avatarRange {@inheritDoc}
+ * @throws HtmlParseException {@inheritDoc}
+ */
+ @Override
+ public void sysEventVanish(DecodedContent content,
+ SeqRange avatarRange )
+ throws HtmlParseException{
+ return;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @param content {@inheritDoc}
+ * @param avatarRange {@inheritDoc}
+ * @throws HtmlParseException {@inheritDoc}
+ */
+ @Override
+ public void sysEventCheckout(DecodedContent content,
+ SeqRange avatarRange )
+ throws HtmlParseException{
+ return;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @param content {@inheritDoc}
+ * @param judgeByRange {@inheritDoc}
+ * @param judgeToRange {@inheritDoc}
+ * @throws HtmlParseException {@inheritDoc}
+ */
+ @Override
+ public void sysEventJudge(DecodedContent content,
+ SeqRange judgeByRange,
+ SeqRange judgeToRange )
+ throws HtmlParseException{
+ return;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @param content {@inheritDoc}
+ * @param guardByRange {@inheritDoc}
+ * @param guardToRange {@inheritDoc}
+ * @throws HtmlParseException {@inheritDoc}
+ */
+ @Override
+ public void sysEventGuard(DecodedContent content,
+ SeqRange guardByRange,
+ SeqRange guardToRange )
+ throws HtmlParseException{
+ return;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @param hour {@inheritDoc}
+ * @param minute {@inheritDoc}
+ * @param minLimit {@inheritDoc}
+ * @param maxLimit {@inheritDoc}
+ * @throws HtmlParseException {@inheritDoc}
+ */
+ @Override
+ public void sysEventAskEntry(int hour, int minute,
+ int minLimit, int maxLimit)
+ throws HtmlParseException{
+ return;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @param hour {@inheritDoc}
+ * @param minute {@inheritDoc}
+ * @throws HtmlParseException {@inheritDoc}
+ */
+ @Override
+ public void sysEventAskCommit(int hour, int minute)
+ throws HtmlParseException{
+ return;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @param content {@inheritDoc}
+ * @param avatarRange {@inheritDoc}
+ * @throws HtmlParseException {@inheritDoc}
+ */
+ @Override
+ public void sysEventNoComment(DecodedContent content,
+ SeqRange avatarRange )
+ throws HtmlParseException{
+ return;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @param winner {@inheritDoc}
+ * @param hour {@inheritDoc}
+ * @param minute {@inheritDoc}
+ * @throws HtmlParseException {@inheritDoc}
+ */
+ @Override
+ public void sysEventStayEpilogue(Team winner, int hour, int minute)
+ throws HtmlParseException{
+ return;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @param content {@inheritDoc}
+ * @param contentRange {@inheritDoc}
+ * @throws HtmlParseException {@inheritDoc}
+ */
+ @Override
+ public void sysEventContent(DecodedContent content,
+ SeqRange contentRange )
+ throws HtmlParseException{
+ return;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @throws HtmlParseException {@inheritDoc}
+ */
+ @Override
+ public void sysEventContentBreak() throws HtmlParseException{
+ return;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @param content {@inheritDoc}
+ * @param anchorRange {@inheritDoc}
+ * @param contentRange {@inheritDoc}
+ * @throws HtmlParseException {@inheritDoc}
+ */
+ @Override
+ public void sysEventContentAnchor(DecodedContent content,
+ SeqRange anchorRange,
+ SeqRange contentRange )
+ throws HtmlParseException{
+ return;
+ }
+
+}
-/*\r
- * marshal handler\r
- *\r
- * License : The MIT License\r
- * Copyright(c) 2009 olyutorskii\r
- */\r
-\r
-package jp.sourceforge.jindolf.parser;\r
-\r
-/**\r
- * 各種XHTMLパース用ハンドラをまとめたインタフェース。\r
- */\r
-public interface HtmlHandler\r
- extends BasicHandler,\r
- TalkHandler,\r
- SysEventHandler {\r
- // NOTHING\r
-}\r
+/*
+ * marshal handler
+ *
+ * License : The MIT License
+ * Copyright(c) 2009 olyutorskii
+ */
+
+package jp.sourceforge.jindolf.parser;
+
+/**
+ * 各種XHTMLパース用ハンドラをまとめたインタフェース。
+ */
+public interface HtmlHandler
+ extends BasicHandler,
+ TalkHandler,
+ SysEventHandler {
+ // NOTHING
+}
-/*\r
- * html parse exception\r
- *\r
- * License : The MIT License\r
- * Copyright(c) 2009 olyutorskii\r
- */\r
-\r
-package jp.sourceforge.jindolf.parser;\r
-\r
-/**\r
- * XHTMLパースの異常系情報。\r
- * {@link HtmlParser}の各ハンドラは、この例外をスローすることで\r
- * パース処理の即時停止を{@link HtmlParser}に指示することができる。\r
- * パース対象({@link DecodedContent})内のパース中断位置を\r
- * 保持することができる。\r
- * 中断位置が不明な場合は負の値が設定される。\r
- */\r
-@SuppressWarnings("serial")\r
-public class HtmlParseException extends Exception{\r
-\r
- private final int charPos;\r
-\r
- /**\r
- * コンストラクタ。\r
- */\r
- public HtmlParseException(){\r
- this(null, -1);\r
- return;\r
- }\r
-\r
- /**\r
- * コンストラクタ。\r
- * @param message メッセージ\r
- */\r
- public HtmlParseException(String message){\r
- this(message, -1);\r
- return;\r
- }\r
-\r
- /**\r
- * コンストラクタ。\r
- * @param charPos パース中断位置\r
- */\r
- public HtmlParseException(int charPos){\r
- this(null, charPos);\r
- return;\r
- }\r
-\r
- /**\r
- * コンストラクタ。\r
- * @param message メッセージ\r
- * @param charPos パース中断位置\r
- */\r
- public HtmlParseException(String message, int charPos){\r
- super(message);\r
- this.charPos = charPos;\r
- return;\r
- }\r
-\r
- /**\r
- * パース中断位置を返す。\r
- * @return パース中断位置\r
- */\r
- public int getCharPos(){\r
- return this.charPos;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * @return {@inheritDoc}\r
- */\r
- @Override\r
- public String getMessage(){\r
- StringBuilder result = new StringBuilder();\r
-\r
- String message = super.getMessage();\r
- if(message != null && message.length() > 0){\r
- result.append(message).append(' ');\r
- }\r
-\r
- result.append("charPos=").append(this.charPos);\r
-\r
- return result.toString();\r
- }\r
-\r
-}\r
+/*
+ * html parse exception
+ *
+ * License : The MIT License
+ * Copyright(c) 2009 olyutorskii
+ */
+
+package jp.sourceforge.jindolf.parser;
+
+/**
+ * XHTMLパースの異常系情報。
+ * {@link HtmlParser}の各ハンドラは、この例外をスローすることで
+ * パース処理の即時停止を{@link HtmlParser}に指示することができる。
+ * パース対象({@link DecodedContent})内のパース中断位置を
+ * 保持することができる。
+ * 中断位置が不明な場合は負の値が設定される。
+ */
+@SuppressWarnings("serial")
+public class HtmlParseException extends Exception{
+
+ private final int charPos;
+
+ /**
+ * コンストラクタ。
+ */
+ public HtmlParseException(){
+ this(null, -1);
+ return;
+ }
+
+ /**
+ * コンストラクタ。
+ * @param message メッセージ
+ */
+ public HtmlParseException(String message){
+ this(message, -1);
+ return;
+ }
+
+ /**
+ * コンストラクタ。
+ * @param charPos パース中断位置
+ */
+ public HtmlParseException(int charPos){
+ this(null, charPos);
+ return;
+ }
+
+ /**
+ * コンストラクタ。
+ * @param message メッセージ
+ * @param charPos パース中断位置
+ */
+ public HtmlParseException(String message, int charPos){
+ super(message);
+ this.charPos = charPos;
+ return;
+ }
+
+ /**
+ * パース中断位置を返す。
+ * @return パース中断位置
+ */
+ public int getCharPos(){
+ return this.charPos;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @return {@inheritDoc}
+ */
+ @Override
+ public String getMessage(){
+ StringBuilder result = new StringBuilder();
+
+ String message = super.getMessage();
+ if(message != null && message.length() > 0){
+ result.append(message).append(' ');
+ }
+
+ result.append("charPos=").append(this.charPos);
+
+ return result.toString();
+ }
+
+}
-/*\r
- * XHTML parser\r
- *\r
- * License : The MIT License\r
- * Copyright(c) 2009 olyutorskii\r
- */\r
-\r
-package jp.sourceforge.jindolf.parser;\r
-\r
-import java.util.regex.Pattern;\r
-import jp.sourceforge.jindolf.corelib.PeriodType;\r
-import jp.sourceforge.jindolf.corelib.VillageState;\r
-\r
-/**\r
- * 人狼BBS各種XHTML文字列のパースを行いハンドラに通知する。\r
- */\r
-public class HtmlParser extends AbstractParser{\r
-\r
- private static final String SP = "\u0020";\r
-\r
-\r
- private BasicHandler basicHandler;\r
- private final TalkParser talkParser = new TalkParser(this);\r
- private final SysEventParser sysEventParser = new SysEventParser(this);\r
-\r
- private final SeqRange rangepool_1 = new SeqRange();\r
- private final SeqRange rangepool_2 = new SeqRange();\r
-\r
- /**\r
- * コンストラクタ。\r
- */\r
- public HtmlParser(){\r
- super();\r
- return;\r
- }\r
-\r
- /**\r
- * {@link BasicHandler}ハンドラを登録する。\r
- * @param basicHandler ハンドラ\r
- */\r
- public void setBasicHandler(BasicHandler basicHandler){\r
- this.basicHandler = basicHandler;\r
- return;\r
- }\r
-\r
- /**\r
- * {@link TalkHandler}ハンドラを登録する。\r
- * @param talkHandler ハンドラ\r
- */\r
- public void setTalkHandler(TalkHandler talkHandler){\r
- this.talkParser.setTalkHandler(talkHandler);\r
- return;\r
- }\r
-\r
- /**\r
- * {@link SysEventHandler}ハンドラを登録する。\r
- * @param handler ハンドラ\r
- */\r
- public void setSysEventHandler(SysEventHandler handler){\r
- this.sysEventParser.setSysEventHandler(handler);\r
- return;\r
- }\r
-\r
- private static final Pattern XMLDECL_PATTERN =\r
- compile("<\\?xml\u0020");\r
- private static final Pattern O_HTML_PATTERN =\r
- compile("<html\u0020");\r
- private static final Pattern TITLE_PATTERN =\r
- compile("<title>([^<]*)</title>");\r
- private static final Pattern O_BODY_PATTERN =\r
- compile("<body>");\r
- private static final Pattern O_DIVMAIN_PATTERN =\r
- compile("<div\u0020class=\"main\">");\r
-\r
- /**\r
- * XHTML先頭部分のパース。\r
- * @throws HtmlParseException パースエラー\r
- */\r
- private void parseHead() throws HtmlParseException{\r
- setContextErrorMessage("lost head part");\r
-\r
- SeqRange titleRange = this.rangepool_1;\r
-\r
- lookingAtAffirm(XMLDECL_PATTERN);\r
- shrinkRegion();\r
-\r
- findAffirm(O_HTML_PATTERN);\r
- shrinkRegion();\r
-\r
- findAffirm(TITLE_PATTERN);\r
- titleRange.setLastMatchedGroupRange(getMatcher(), 1);\r
- shrinkRegion();\r
-\r
- this.basicHandler.pageTitle(getContent(), titleRange);\r
-\r
- findAffirm(O_BODY_PATTERN);\r
- shrinkRegion();\r
-\r
- findAffirm(O_DIVMAIN_PATTERN);\r
- shrinkRegion();\r
-\r
- return;\r
- }\r
-\r
- private static final Pattern LOGINFORM_PATTERN =\r
- compile(\r
- "("\r
- +"<form"\r
- +SP + "action=\"index\\.rb\""\r
- +SP + "method=\"post\""\r
- +SP + "class=\"login_form\""\r
- +">"\r
- + ")|("\r
- +"<div"\r
- +SP + "class=\"login_form\""\r
- +">"\r
- + ")"\r
- );\r
- private static final Pattern C_EDIV_PATTERN =\r
- compile(\r
- SP_I\r
- + "<a\u0020href=\"[^\"]*\">[^<]*</a>"\r
- + SP_I\r
- + "</div>"\r
- );\r
- private static final Pattern USERID_PATTERN =\r
- compile(\r
- "name=\"user_id\""\r
- + SP\r
- + "value=\"([^\"]*)\""\r
- );\r
- private static final Pattern C_FORM_PATTERN =\r
- compile("</form>");\r
-\r
- /**\r
- * ログインフォームのパース。\r
- * ログイン名までの認識を確認したのはF国のみ。\r
- * @throws HtmlParseException パースエラー\r
- */\r
- private void parseLoginForm() throws HtmlParseException{\r
- setContextErrorMessage("lost login form");\r
-\r
- SeqRange accountRange = this.rangepool_1;\r
-\r
- boolean isLand_E_Form;\r
- findAffirm(LOGINFORM_PATTERN);\r
- if(isGroupMatched(1)){\r
- isLand_E_Form = false;\r
- }else{ // E国ログインフォーム検出\r
- isLand_E_Form = true;\r
- }\r
- shrinkRegion();\r
-\r
- if(isLand_E_Form){\r
- lookingAtAffirm(C_EDIV_PATTERN);\r
- shrinkRegion();\r
- return;\r
- }else{\r
- findAffirm(USERID_PATTERN);\r
- accountRange.setLastMatchedGroupRange(getMatcher(), 1);\r
- shrinkRegion();\r
-\r
- if(accountRange.length() > 0){\r
- this.basicHandler\r
- .loginName(getContent(), accountRange);\r
- }\r
-\r
- findAffirm(C_FORM_PATTERN);\r
- shrinkRegion();\r
- }\r
-\r
- return;\r
- }\r
-\r
- private static final Pattern VILLAGEINFO_PATTERN =\r
- compile(\r
- "([^<]+?)" +SP_I // 最短一致数量子\r
- +"<strong>"\r
- +"\uff08"\r
- +"([0-9]+)" // 月\r
- +"/"\r
- +"([0-9]+)" // 日\r
- +SP\r
- +"(?:(?:(午前)|(午後))\u0020)?" // AMPM\r
- +"([0-9]+)" // 時\r
- +"(?:時\u0020|\\:)"\r
- +"([0-9]+)" // 分\r
- +"分?\u0020に更新"\r
- +"\uff09"\r
- +"</strong>"\r
- );\r
-\r
- /**\r
- * 村に関する各種情報をパース。\r
- * @throws HtmlParseException パースエラー\r
- */\r
- private void parseVillageInfo() throws HtmlParseException{\r
- setContextErrorMessage("lose village information");\r
-\r
- SeqRange villageRange = this.rangepool_1;\r
-\r
- sweepSpace();\r
-\r
- lookingAtAffirm(VILLAGEINFO_PATTERN);\r
- villageRange.setLastMatchedGroupRange(getMatcher(), 1);\r
-\r
- int month = parseGroupedInt(2);\r
- int day = parseGroupedInt(3);\r
- int hour = parseGroupedInt(6);\r
- int minute = parseGroupedInt(7);\r
- if(isGroupMatched(5)){ // 午後指定\r
- hour = (hour + 12) % 24;\r
- }\r
- shrinkRegion();\r
-\r
- this.basicHandler.villageName(getContent(), villageRange);\r
- this.basicHandler.commitTime(month, day, hour, minute);\r
-\r
- return;\r
- }\r
-\r
- private static final Pattern O_PARAG_PATTERN = compile("<p>");\r
- private static final Pattern PERIODLINK_PATTERN =\r
- compile(\r
- "("\r
- + "<span\u0020class=\"time\">"\r
- +")|(?:"\r
- + "<a\u0020href=\"([^\"]*)\">"\r
- +")|("\r
- + "</p>"\r
- +")"\r
- );\r
- private static final Pattern PERIOD_PATTERN =\r
- compile(\r
- "(プロローグ)" +\r
- "|"+\r
- "(エピローグ)" +\r
- "|"+\r
- "(終了)" +\r
- "|"+\r
- "([0-9]+)日目"\r
- );\r
- private static final Pattern C_SPAN_PATTERN = compile("</span>");\r
- private static final Pattern C_ANCHOR_PATTERN = compile("</a>");\r
-\r
- /**\r
- * Period間リンクをパース。\r
- * @throws HtmlParseException パースエラー\r
- */\r
- private void parsePeriodLink() throws HtmlParseException{\r
- setContextErrorMessage("lost period link");\r
-\r
- SeqRange anchorRange = this.rangepool_1;\r
-\r
- findAffirm(O_PARAG_PATTERN);\r
- shrinkRegion();\r
-\r
- for(;;){\r
- Pattern closePattern;\r
- anchorRange.setInvalid();\r
-\r
- sweepSpace();\r
- lookingAtAffirm(PERIODLINK_PATTERN);\r
- if(isGroupMatched(1)){\r
- closePattern = C_SPAN_PATTERN;\r
- }else if(isGroupMatched(2)){\r
- closePattern = C_ANCHOR_PATTERN;\r
- anchorRange.setLastMatchedGroupRange(getMatcher(), 2);\r
- }else if(isGroupMatched(3)){\r
- shrinkRegion();\r
- break;\r
- }else{\r
- assert false;\r
- throw buildParseException();\r
- }\r
- shrinkRegion();\r
-\r
- int day = -1;\r
- PeriodType periodType = null;\r
- lookingAtAffirm(PERIOD_PATTERN);\r
- if(isGroupMatched(1)){\r
- periodType = PeriodType.PROLOGUE;\r
- }else if(isGroupMatched(2)){\r
- periodType = PeriodType.EPILOGUE;\r
- }else if(isGroupMatched(3)){\r
- periodType = null;\r
- }else if(isGroupMatched(4)){\r
- periodType = PeriodType.PROGRESS;\r
- day = parseGroupedInt(4);\r
- }else{\r
- assert false;\r
- throw buildParseException();\r
- }\r
- shrinkRegion();\r
-\r
- lookingAtAffirm(closePattern);\r
- shrinkRegion();\r
-\r
- this.basicHandler.periodLink(getContent(),\r
- anchorRange,\r
- periodType, day );\r
- }\r
-\r
- return;\r
- }\r
-\r
- private static final Pattern O_MESSAGE_PATTERN =\r
- compile("<div\u0020class=\"message(?:\u0020ch[0-9]+)?\">");\r
- private static final Pattern O_RELOAD_PATTERN =\r
- compile("<div\u0020id=\"reload\">");\r
- private static final Pattern O_MSGKIND_PATTERN =\r
- compile(\r
- "(?:"\r
- +"<div\u0020class=\"(?:(announce)|(order)|(extra))\">"\r
- +")|(?:"\r
- +"(?:"\r
- +"(?:<a name=\"[^\"]*\">)?"\r
- +SP_I\r
- +"<span\u0020class=\"mes_no\">"\r
- +"([0-9]+)\\."\r
- +"</span>)?"\r
- +SP_I\r
- +"(?:</a>)?"\r
- +SP_I\r
- +"<a\u0020name=\"([^\"]*)\"(?:\u0020class=\"ch_name\")?>"\r
- +")"\r
- );\r
- private static final Pattern C_DIV_PATTERN = compile("</div>");\r
-\r
- /**\r
- * 各種メッセージをパース。\r
- * @throws HtmlParseException パースエラー\r
- */\r
- private void parseMessage() throws HtmlParseException{\r
- setContextErrorMessage("lost message");\r
-\r
- boolean skipGarbage = true;\r
-\r
- for(;;){\r
- sweepSpace();\r
-\r
- boolean matched;\r
- if(skipGarbage){\r
- skipGarbage = false;\r
- matched = findProbe(O_MESSAGE_PATTERN); // 最初の1回のみ\r
- }else{\r
- matched = lookingAtProbe(O_MESSAGE_PATTERN);\r
- }\r
- if( ! matched ){\r
- matched = lookingAtProbe(O_RELOAD_PATTERN);\r
- if(matched){\r
- shrinkRegion();\r
- findAffirm(C_DIV_PATTERN);\r
- shrinkRegion();\r
- continue;\r
- }\r
- break;\r
- }\r
- shrinkRegion();\r
-\r
- dispatchFamily();\r
-\r
- lookingAtAffirm(C_DIV_PATTERN);\r
- shrinkRegion();\r
- }\r
-\r
- return;\r
- }\r
-\r
- /**\r
- * イベント種別によって処理を振り分ける。\r
- * @throws HtmlParseException パースエラー\r
- */\r
- private void dispatchFamily() throws HtmlParseException{\r
- sweepSpace();\r
-\r
- SeqRange nameRange = this.rangepool_1;\r
-\r
- lookingAtAffirm(O_MSGKIND_PATTERN);\r
- if(isGroupMatched(1)){\r
- shrinkRegion();\r
- this.sysEventParser.parseAnnounce();\r
- }else if(isGroupMatched(2)){\r
- shrinkRegion();\r
- this.sysEventParser.parseOrder();\r
- }else if(isGroupMatched(3)){\r
- shrinkRegion();\r
- this.sysEventParser.parseExtra();\r
- }else if(isGroupMatched(5)){\r
- nameRange.setLastMatchedGroupRange(getMatcher(), 5);\r
- int talkNo = -1;\r
- if(isGroupMatched(4)){\r
- talkNo = parseGroupedInt(4);\r
- }\r
- shrinkRegion();\r
- this.talkParser.parseTalk(talkNo, nameRange);\r
- }else{\r
- assert false;\r
- throw buildParseException();\r
- }\r
-\r
- return;\r
- }\r
-\r
- private static final Pattern O_LISTTABLE_PATTERN =\r
- compile("<table\u0020class=\"list\">");\r
- private static final Pattern ACTIVEVILLAGE =\r
- compile(\r
- "("\r
- +"</table>"\r
- +")|(?:"\r
- +"<tr><td>"\r
- +"<a\u0020href=\"([^\"]*)\">([^<]*)</a>"\r
- +"\u0020<strong>\uff08"\r
- +"(?:(?:(午前)|(午後))\u0020)?" // AMPM\r
- +"([0-9]+)" // 時\r
- +"(?:時\u0020|\\:)"\r
- +"([0-9]+)" // 分\r
- +"分?\u0020更新"\r
- +"\uff09</strong>"\r
- +"</td><td>(?:"\r
- +"[^<]*"\r
- + "(参加者募集中です。)"\r
- +"|(開始待ちです。)"\r
- +"|(進行中です。)"\r
- +"|(勝敗が決定しました。)"\r
- +"|(終了・ログ公開中。)"\r
- +")</td></tr>"\r
- +")"\r
- );\r
-\r
- /**\r
- * トップページの村一覧表のパース。\r
- * @throws HtmlParseException パースエラー\r
- */\r
- private void parseTopList() throws HtmlParseException{\r
- setContextErrorMessage("lost village list");\r
-\r
- SeqRange anchorRange = this.rangepool_1;\r
- SeqRange villageRange = this.rangepool_2;\r
-\r
- if( ! findProbe(O_LISTTABLE_PATTERN) ) return;\r
- shrinkRegion();\r
-\r
- for(;;){\r
- lookingAtAffirm(ACTIVEVILLAGE);\r
- if(isGroupMatched(1)) break;\r
- anchorRange .setLastMatchedGroupRange(getMatcher(), 2);\r
- villageRange.setLastMatchedGroupRange(getMatcher(), 3);\r
- int hour = parseGroupedInt(6);\r
- if(isGroupMatched(5)){\r
- hour = (hour + 12) % 24;\r
- }\r
- int minute = parseGroupedInt(7);\r
-\r
- VillageState state;\r
- if(isGroupMatched(8)){\r
- state = VillageState.PROLOGUE;\r
- }else if(isGroupMatched(9)){\r
- state = VillageState.PROLOGUE;\r
- }else if(isGroupMatched(10)){\r
- state = VillageState.PROGRESS;\r
- }else if(isGroupMatched(11)){\r
- state = VillageState.EPILOGUE;\r
- }else if(isGroupMatched(12)){\r
- state = VillageState.GAMEOVER;\r
- }else{\r
- assert false;\r
- throw buildParseException();\r
- }\r
-\r
- shrinkRegion();\r
-\r
- sweepSpace();\r
-\r
- this.basicHandler.villageRecord(getContent(),\r
- anchorRange,\r
- villageRange,\r
- hour, minute,\r
- state );\r
- }\r
-\r
- return;\r
- }\r
-\r
- private static final Pattern O_LISTLOG_PATTERN =\r
- compile(\r
- "<a\u0020href=\"(index[^\"]*(?:ready_0|000_ready))\">"\r
- +"([^<]*)"\r
- +"</a><br\u0020/>"\r
- );\r
-\r
- /**\r
- * 村一覧ページのパース。\r
- * @throws HtmlParseException パースエラー\r
- */\r
- private void parseLogList() throws HtmlParseException{\r
- setContextErrorMessage("lost village list");\r
-\r
- SeqRange anchorRange = this.rangepool_1;\r
- SeqRange villageRange = this.rangepool_2;\r
-\r
- boolean is1st = true;\r
- for(;;){\r
- boolean matched;\r
- if(is1st){\r
- matched = findProbe(O_LISTLOG_PATTERN);\r
- is1st = false;\r
- }else{\r
- matched = lookingAtProbe(O_LISTLOG_PATTERN);\r
- }\r
- if( ! matched ) break;\r
-\r
- anchorRange .setLastMatchedGroupRange(getMatcher(), 1);\r
- villageRange.setLastMatchedGroupRange(getMatcher(), 2);\r
-\r
- shrinkRegion();\r
-\r
- this.basicHandler.villageRecord(getContent(),\r
- anchorRange,\r
- villageRange,\r
- -1, -1,\r
- VillageState.GAMEOVER );\r
- }\r
-\r
- return;\r
- }\r
-\r
- private static final Pattern C_BODY_PATTERN =\r
- compile("</body>");\r
- private static final Pattern C_HTML_PATTERN =\r
- compile(SP_I+ "</html>" +SP_I);\r
-\r
- /**\r
- * XHTML末尾のパース。\r
- * @throws HtmlParseException パースエラー\r
- */\r
- private void parseTail() throws HtmlParseException{\r
- setContextErrorMessage("lost last part");\r
-\r
- findAffirm(C_BODY_PATTERN);\r
- shrinkRegion();\r
-\r
- matchesAffirm(C_HTML_PATTERN);\r
- shrinkRegion();\r
-\r
- return;\r
- }\r
-\r
- private static final Pattern LISTTITLE_PATTERN =\r
- compile("終了した村の記録");\r
-\r
- /**\r
- * 人狼BBSのページ種別を自動認識しつつパースする。\r
- * @param content パース対象の文字列\r
- * @throws HtmlParseException パースエラー\r
- */\r
- public void parseAutomatic(DecodedContent content)\r
- throws HtmlParseException{\r
- setContent(content);\r
-\r
- this.basicHandler.startParse(getContent());\r
-\r
- parseHead();\r
-\r
- sweepSpace();\r
-\r
- if(lookingAtProbe(LISTTITLE_PATTERN)){\r
- shrinkRegion();\r
- this.basicHandler.pageType(PageType.VILLAGELIST_PAGE);\r
- parseLogList();\r
- }else{\r
- parseLoginForm();\r
- sweepSpace();\r
- if(lookingAtProbe(O_PARAG_PATTERN)){\r
- shrinkRegion();\r
- this.basicHandler.pageType(PageType.TOP_PAGE);\r
- parseTopList();\r
- }else{\r
- this.basicHandler.pageType(PageType.PERIOD_PAGE);\r
- parseVillageInfo();\r
- parsePeriodLink();\r
- parseMessage();\r
- }\r
- }\r
-\r
- parseTail();\r
-\r
- this.basicHandler.endParse();\r
-\r
- reset();\r
-\r
- return;\r
- }\r
-\r
-}\r
+/*
+ * XHTML parser
+ *
+ * License : The MIT License
+ * Copyright(c) 2009 olyutorskii
+ */
+
+package jp.sourceforge.jindolf.parser;
+
+import java.util.regex.Pattern;
+import jp.sourceforge.jindolf.corelib.PeriodType;
+import jp.sourceforge.jindolf.corelib.VillageState;
+
+/**
+ * 人狼BBS各種XHTML文字列のパースを行いハンドラに通知する。
+ */
+public class HtmlParser extends AbstractParser{
+
+ private static final String SP = "\u0020";
+
+
+ private BasicHandler basicHandler;
+ private final TalkParser talkParser = new TalkParser(this);
+ private final SysEventParser sysEventParser = new SysEventParser(this);
+
+ private final SeqRange rangepool_1 = new SeqRange();
+ private final SeqRange rangepool_2 = new SeqRange();
+
+ /**
+ * コンストラクタ。
+ */
+ public HtmlParser(){
+ super();
+ return;
+ }
+
+ /**
+ * {@link BasicHandler}ハンドラを登録する。
+ * @param basicHandler ハンドラ
+ */
+ public void setBasicHandler(BasicHandler basicHandler){
+ this.basicHandler = basicHandler;
+ return;
+ }
+
+ /**
+ * {@link TalkHandler}ハンドラを登録する。
+ * @param talkHandler ハンドラ
+ */
+ public void setTalkHandler(TalkHandler talkHandler){
+ this.talkParser.setTalkHandler(talkHandler);
+ return;
+ }
+
+ /**
+ * {@link SysEventHandler}ハンドラを登録する。
+ * @param handler ハンドラ
+ */
+ public void setSysEventHandler(SysEventHandler handler){
+ this.sysEventParser.setSysEventHandler(handler);
+ return;
+ }
+
+ private static final Pattern XMLDECL_PATTERN =
+ compile("<\\?xml\u0020");
+ private static final Pattern O_HTML_PATTERN =
+ compile("<html\u0020");
+ private static final Pattern TITLE_PATTERN =
+ compile("<title>([^<]*)</title>");
+ private static final Pattern O_BODY_PATTERN =
+ compile("<body>");
+ private static final Pattern O_DIVMAIN_PATTERN =
+ compile("<div\u0020class=\"main\">");
+
+ /**
+ * XHTML先頭部分のパース。
+ * @throws HtmlParseException パースエラー
+ */
+ private void parseHead() throws HtmlParseException{
+ setContextErrorMessage("lost head part");
+
+ SeqRange titleRange = this.rangepool_1;
+
+ lookingAtAffirm(XMLDECL_PATTERN);
+ shrinkRegion();
+
+ findAffirm(O_HTML_PATTERN);
+ shrinkRegion();
+
+ findAffirm(TITLE_PATTERN);
+ titleRange.setLastMatchedGroupRange(getMatcher(), 1);
+ shrinkRegion();
+
+ this.basicHandler.pageTitle(getContent(), titleRange);
+
+ findAffirm(O_BODY_PATTERN);
+ shrinkRegion();
+
+ findAffirm(O_DIVMAIN_PATTERN);
+ shrinkRegion();
+
+ return;
+ }
+
+ private static final Pattern LOGINFORM_PATTERN =
+ compile(
+ "("
+ +"<form"
+ +SP + "action=\"index\\.rb\""
+ +SP + "method=\"post\""
+ +SP + "class=\"login_form\""
+ +">"
+ + ")|("
+ +"<div"
+ +SP + "class=\"login_form\""
+ +">"
+ + ")"
+ );
+ private static final Pattern C_EDIV_PATTERN =
+ compile(
+ SP_I
+ + "<a\u0020href=\"[^\"]*\">[^<]*</a>"
+ + SP_I
+ + "</div>"
+ );
+ private static final Pattern USERID_PATTERN =
+ compile(
+ "name=\"user_id\""
+ + SP
+ + "value=\"([^\"]*)\""
+ );
+ private static final Pattern C_FORM_PATTERN =
+ compile("</form>");
+
+ /**
+ * ログインフォームのパース。
+ * ログイン名までの認識を確認したのはF国のみ。
+ * @throws HtmlParseException パースエラー
+ */
+ private void parseLoginForm() throws HtmlParseException{
+ setContextErrorMessage("lost login form");
+
+ SeqRange accountRange = this.rangepool_1;
+
+ boolean isLand_E_Form;
+ findAffirm(LOGINFORM_PATTERN);
+ if(isGroupMatched(1)){
+ isLand_E_Form = false;
+ }else{ // E国ログインフォーム検出
+ isLand_E_Form = true;
+ }
+ shrinkRegion();
+
+ if(isLand_E_Form){
+ lookingAtAffirm(C_EDIV_PATTERN);
+ shrinkRegion();
+ return;
+ }else{
+ findAffirm(USERID_PATTERN);
+ accountRange.setLastMatchedGroupRange(getMatcher(), 1);
+ shrinkRegion();
+
+ if(accountRange.length() > 0){
+ this.basicHandler
+ .loginName(getContent(), accountRange);
+ }
+
+ findAffirm(C_FORM_PATTERN);
+ shrinkRegion();
+ }
+
+ return;
+ }
+
+ private static final Pattern VILLAGEINFO_PATTERN =
+ compile(
+ "([^<]+?)" +SP_I // 最短一致数量子
+ +"<strong>"
+ +"\uff08"
+ +"([0-9]+)" // 月
+ +"/"
+ +"([0-9]+)" // 日
+ +SP
+ +"(?:(?:(午前)|(午後))\u0020)?" // AMPM
+ +"([0-9]+)" // 時
+ +"(?:時\u0020|\\:)"
+ +"([0-9]+)" // 分
+ +"分?\u0020に更新"
+ +"\uff09"
+ +"</strong>"
+ );
+
+ /**
+ * 村に関する各種情報をパース。
+ * @throws HtmlParseException パースエラー
+ */
+ private void parseVillageInfo() throws HtmlParseException{
+ setContextErrorMessage("lose village information");
+
+ SeqRange villageRange = this.rangepool_1;
+
+ sweepSpace();
+
+ lookingAtAffirm(VILLAGEINFO_PATTERN);
+ villageRange.setLastMatchedGroupRange(getMatcher(), 1);
+
+ int month = parseGroupedInt(2);
+ int day = parseGroupedInt(3);
+ int hour = parseGroupedInt(6);
+ int minute = parseGroupedInt(7);
+ if(isGroupMatched(5)){ // 午後指定
+ hour = (hour + 12) % 24;
+ }
+ shrinkRegion();
+
+ this.basicHandler.villageName(getContent(), villageRange);
+ this.basicHandler.commitTime(month, day, hour, minute);
+
+ return;
+ }
+
+ private static final Pattern O_PARAG_PATTERN = compile("<p>");
+ private static final Pattern PERIODLINK_PATTERN =
+ compile(
+ "("
+ + "<span\u0020class=\"time\">"
+ +")|(?:"
+ + "<a\u0020href=\"([^\"]*)\">"
+ +")|("
+ + "</p>"
+ +")"
+ );
+ private static final Pattern PERIOD_PATTERN =
+ compile(
+ "(プロローグ)" +
+ "|"+
+ "(エピローグ)" +
+ "|"+
+ "(終了)" +
+ "|"+
+ "([0-9]+)日目"
+ );
+ private static final Pattern C_SPAN_PATTERN = compile("</span>");
+ private static final Pattern C_ANCHOR_PATTERN = compile("</a>");
+
+ /**
+ * Period間リンクをパース。
+ * @throws HtmlParseException パースエラー
+ */
+ private void parsePeriodLink() throws HtmlParseException{
+ setContextErrorMessage("lost period link");
+
+ SeqRange anchorRange = this.rangepool_1;
+
+ findAffirm(O_PARAG_PATTERN);
+ shrinkRegion();
+
+ for(;;){
+ Pattern closePattern;
+ anchorRange.setInvalid();
+
+ sweepSpace();
+ lookingAtAffirm(PERIODLINK_PATTERN);
+ if(isGroupMatched(1)){
+ closePattern = C_SPAN_PATTERN;
+ }else if(isGroupMatched(2)){
+ closePattern = C_ANCHOR_PATTERN;
+ anchorRange.setLastMatchedGroupRange(getMatcher(), 2);
+ }else if(isGroupMatched(3)){
+ shrinkRegion();
+ break;
+ }else{
+ assert false;
+ throw buildParseException();
+ }
+ shrinkRegion();
+
+ int day = -1;
+ PeriodType periodType = null;
+ lookingAtAffirm(PERIOD_PATTERN);
+ if(isGroupMatched(1)){
+ periodType = PeriodType.PROLOGUE;
+ }else if(isGroupMatched(2)){
+ periodType = PeriodType.EPILOGUE;
+ }else if(isGroupMatched(3)){
+ periodType = null;
+ }else if(isGroupMatched(4)){
+ periodType = PeriodType.PROGRESS;
+ day = parseGroupedInt(4);
+ }else{
+ assert false;
+ throw buildParseException();
+ }
+ shrinkRegion();
+
+ lookingAtAffirm(closePattern);
+ shrinkRegion();
+
+ this.basicHandler.periodLink(getContent(),
+ anchorRange,
+ periodType, day );
+ }
+
+ return;
+ }
+
+ private static final Pattern O_MESSAGE_PATTERN =
+ compile("<div\u0020class=\"message(?:\u0020ch[0-9]+)?\">");
+ private static final Pattern O_RELOAD_PATTERN =
+ compile("<div\u0020id=\"reload\">");
+ private static final Pattern O_MSGKIND_PATTERN =
+ compile(
+ "(?:"
+ +"<div\u0020class=\"(?:(announce)|(order)|(extra))\">"
+ +")|(?:"
+ +"(?:"
+ +"(?:<a name=\"[^\"]*\">)?"
+ +SP_I
+ +"<span\u0020class=\"mes_no\">"
+ +"([0-9]+)\\."
+ +"</span>)?"
+ +SP_I
+ +"(?:</a>)?"
+ +SP_I
+ +"<a\u0020name=\"([^\"]*)\"(?:\u0020class=\"ch_name\")?>"
+ +")"
+ );
+ private static final Pattern C_DIV_PATTERN = compile("</div>");
+
+ /**
+ * 各種メッセージをパース。
+ * @throws HtmlParseException パースエラー
+ */
+ private void parseMessage() throws HtmlParseException{
+ setContextErrorMessage("lost message");
+
+ boolean skipGarbage = true;
+
+ for(;;){
+ sweepSpace();
+
+ boolean matched;
+ if(skipGarbage){
+ skipGarbage = false;
+ matched = findProbe(O_MESSAGE_PATTERN); // 最初の1回のみ
+ }else{
+ matched = lookingAtProbe(O_MESSAGE_PATTERN);
+ }
+ if( ! matched ){
+ matched = lookingAtProbe(O_RELOAD_PATTERN);
+ if(matched){
+ shrinkRegion();
+ findAffirm(C_DIV_PATTERN);
+ shrinkRegion();
+ continue;
+ }
+ break;
+ }
+ shrinkRegion();
+
+ dispatchFamily();
+
+ lookingAtAffirm(C_DIV_PATTERN);
+ shrinkRegion();
+ }
+
+ return;
+ }
+
+ /**
+ * イベント種別によって処理を振り分ける。
+ * @throws HtmlParseException パースエラー
+ */
+ private void dispatchFamily() throws HtmlParseException{
+ sweepSpace();
+
+ SeqRange nameRange = this.rangepool_1;
+
+ lookingAtAffirm(O_MSGKIND_PATTERN);
+ if(isGroupMatched(1)){
+ shrinkRegion();
+ this.sysEventParser.parseAnnounce();
+ }else if(isGroupMatched(2)){
+ shrinkRegion();
+ this.sysEventParser.parseOrder();
+ }else if(isGroupMatched(3)){
+ shrinkRegion();
+ this.sysEventParser.parseExtra();
+ }else if(isGroupMatched(5)){
+ nameRange.setLastMatchedGroupRange(getMatcher(), 5);
+ int talkNo = -1;
+ if(isGroupMatched(4)){
+ talkNo = parseGroupedInt(4);
+ }
+ shrinkRegion();
+ this.talkParser.parseTalk(talkNo, nameRange);
+ }else{
+ assert false;
+ throw buildParseException();
+ }
+
+ return;
+ }
+
+ private static final Pattern O_LISTTABLE_PATTERN =
+ compile("<table\u0020class=\"list\">");
+ private static final Pattern ACTIVEVILLAGE =
+ compile(
+ "("
+ +"</table>"
+ +")|(?:"
+ +"<tr><td>"
+ +"<a\u0020href=\"([^\"]*)\">([^<]*)</a>"
+ +"\u0020<strong>\uff08"
+ +"(?:(?:(午前)|(午後))\u0020)?" // AMPM
+ +"([0-9]+)" // 時
+ +"(?:時\u0020|\\:)"
+ +"([0-9]+)" // 分
+ +"分?\u0020更新"
+ +"\uff09</strong>"
+ +"</td><td>(?:"
+ +"[^<]*"
+ + "(参加者募集中です。)"
+ +"|(開始待ちです。)"
+ +"|(進行中です。)"
+ +"|(勝敗が決定しました。)"
+ +"|(終了・ログ公開中。)"
+ +")</td></tr>"
+ +")"
+ );
+
+ /**
+ * トップページの村一覧表のパース。
+ * @throws HtmlParseException パースエラー
+ */
+ private void parseTopList() throws HtmlParseException{
+ setContextErrorMessage("lost village list");
+
+ SeqRange anchorRange = this.rangepool_1;
+ SeqRange villageRange = this.rangepool_2;
+
+ if( ! findProbe(O_LISTTABLE_PATTERN) ) return;
+ shrinkRegion();
+
+ for(;;){
+ lookingAtAffirm(ACTIVEVILLAGE);
+ if(isGroupMatched(1)) break;
+ anchorRange .setLastMatchedGroupRange(getMatcher(), 2);
+ villageRange.setLastMatchedGroupRange(getMatcher(), 3);
+ int hour = parseGroupedInt(6);
+ if(isGroupMatched(5)){
+ hour = (hour + 12) % 24;
+ }
+ int minute = parseGroupedInt(7);
+
+ VillageState state;
+ if(isGroupMatched(8)){
+ state = VillageState.PROLOGUE;
+ }else if(isGroupMatched(9)){
+ state = VillageState.PROLOGUE;
+ }else if(isGroupMatched(10)){
+ state = VillageState.PROGRESS;
+ }else if(isGroupMatched(11)){
+ state = VillageState.EPILOGUE;
+ }else if(isGroupMatched(12)){
+ state = VillageState.GAMEOVER;
+ }else{
+ assert false;
+ throw buildParseException();
+ }
+
+ shrinkRegion();
+
+ sweepSpace();
+
+ this.basicHandler.villageRecord(getContent(),
+ anchorRange,
+ villageRange,
+ hour, minute,
+ state );
+ }
+
+ return;
+ }
+
+ private static final Pattern O_LISTLOG_PATTERN =
+ compile(
+ "<a\u0020href=\"(index[^\"]*(?:ready_0|000_ready))\">"
+ +"([^<]*)"
+ +"</a><br\u0020/>"
+ );
+
+ /**
+ * 村一覧ページのパース。
+ * @throws HtmlParseException パースエラー
+ */
+ private void parseLogList() throws HtmlParseException{
+ setContextErrorMessage("lost village list");
+
+ SeqRange anchorRange = this.rangepool_1;
+ SeqRange villageRange = this.rangepool_2;
+
+ boolean is1st = true;
+ for(;;){
+ boolean matched;
+ if(is1st){
+ matched = findProbe(O_LISTLOG_PATTERN);
+ is1st = false;
+ }else{
+ matched = lookingAtProbe(O_LISTLOG_PATTERN);
+ }
+ if( ! matched ) break;
+
+ anchorRange .setLastMatchedGroupRange(getMatcher(), 1);
+ villageRange.setLastMatchedGroupRange(getMatcher(), 2);
+
+ shrinkRegion();
+
+ this.basicHandler.villageRecord(getContent(),
+ anchorRange,
+ villageRange,
+ -1, -1,
+ VillageState.GAMEOVER );
+ }
+
+ return;
+ }
+
+ private static final Pattern C_BODY_PATTERN =
+ compile("</body>");
+ private static final Pattern C_HTML_PATTERN =
+ compile(SP_I+ "</html>" +SP_I);
+
+ /**
+ * XHTML末尾のパース。
+ * @throws HtmlParseException パースエラー
+ */
+ private void parseTail() throws HtmlParseException{
+ setContextErrorMessage("lost last part");
+
+ findAffirm(C_BODY_PATTERN);
+ shrinkRegion();
+
+ matchesAffirm(C_HTML_PATTERN);
+ shrinkRegion();
+
+ return;
+ }
+
+ private static final Pattern LISTTITLE_PATTERN =
+ compile("終了した村の記録");
+
+ /**
+ * 人狼BBSのページ種別を自動認識しつつパースする。
+ * @param content パース対象の文字列
+ * @throws HtmlParseException パースエラー
+ */
+ public void parseAutomatic(DecodedContent content)
+ throws HtmlParseException{
+ setContent(content);
+
+ this.basicHandler.startParse(getContent());
+
+ parseHead();
+
+ sweepSpace();
+
+ if(lookingAtProbe(LISTTITLE_PATTERN)){
+ shrinkRegion();
+ this.basicHandler.pageType(PageType.VILLAGELIST_PAGE);
+ parseLogList();
+ }else{
+ parseLoginForm();
+ sweepSpace();
+ if(lookingAtProbe(O_PARAG_PATTERN)){
+ shrinkRegion();
+ this.basicHandler.pageType(PageType.TOP_PAGE);
+ parseTopList();
+ }else{
+ this.basicHandler.pageType(PageType.PERIOD_PAGE);
+ parseVillageInfo();
+ parsePeriodLink();
+ parseMessage();
+ }
+ }
+
+ parseTail();
+
+ this.basicHandler.endParse();
+
+ reset();
+
+ return;
+ }
+
+}
-/*\r
- * page type\r
- *\r
- * License : The MIT License\r
- * Copyright(c) 2009 olyutorskii\r
- */\r
-\r
-package jp.sourceforge.jindolf.parser;\r
-\r
-/**\r
- * 人狼BBSサーバが生成するXHTMLページの種別。\r
- */\r
-public enum PageType{\r
-\r
- /** トップページ。 */\r
- TOP_PAGE,\r
- /** 終了した村一覧。古国には存在しない。 */\r
- VILLAGELIST_PAGE,\r
- /** 各村の各日々。 */\r
- PERIOD_PAGE,\r
- ;\r
-\r
-}\r
+/*
+ * page type
+ *
+ * License : The MIT License
+ * Copyright(c) 2009 olyutorskii
+ */
+
+package jp.sourceforge.jindolf.parser;
+
+/**
+ * 人狼BBSサーバが生成するXHTMLページの種別。
+ */
+public enum PageType{
+
+ /** トップページ。 */
+ TOP_PAGE,
+ /** 終了した村一覧。古国には存在しない。 */
+ VILLAGELIST_PAGE,
+ /** 各村の各日々。 */
+ PERIOD_PAGE,
+ ;
+
+}
-/*\r
- * range of string\r
- *\r
- * License : The MIT License\r
- * Copyright(c) 2009 olyutorskii\r
- */\r
-\r
-package jp.sourceforge.jindolf.parser;\r
-\r
-import java.util.regex.MatchResult;\r
-\r
-/**\r
- * 文字列の範囲を表す。\r
- * 範囲は開始位置と終了位置で表される。\r
- * 開始位置と終了位置が同じ場合、長さ0の範囲とみなされる。\r
- * 開始位置0は文字列の左端を表す。\r
- * 開始位置が負の場合、もしくは開始位置より終了位置が小さい場合、\r
- * このオブジェクトは無効とみなされる。\r
- */\r
-public class SeqRange{\r
-\r
- private int startPos;\r
- private int endPos;\r
-\r
- /**\r
- * コンストラクタ。\r
- * 開始位置、終了位置ともに無効状態となる。\r
- */\r
- public SeqRange(){\r
- this(-1, -1);\r
- return;\r
- }\r
-\r
- /**\r
- * コンストラクタ。\r
- * @param startPos 開始位置\r
- * @param endPos 終了位置\r
- */\r
- public SeqRange(int startPos, int endPos){\r
- super();\r
- this.startPos = startPos;\r
- this.endPos = endPos;\r
- return;\r
- }\r
-\r
- /**\r
- * 開始位置を設定する。\r
- * @param startPos 開始位置\r
- */\r
- public void setStartPos(int startPos){\r
- this.startPos = startPos;\r
- return;\r
- }\r
-\r
- /**\r
- * 終了位置を設定する。\r
- * @param endPos 終了位置\r
- */\r
- public void setEndPos(int endPos){\r
- this.endPos = endPos;\r
- return;\r
- }\r
-\r
- /**\r
- * 開始位置と終了位置を設定する。\r
- * @param startPosition 開始位置\r
- * @param endPosition 終了位置\r
- */\r
- public void setRange(int startPosition, int endPosition){\r
- this.startPos = startPosition;\r
- this.endPos = endPosition;\r
- return;\r
- }\r
-\r
- /**\r
- * 最後にマッチした前方参照グループの範囲で設定する。\r
- * @param result 正規表現マッチ結果\r
- * @param groupId グループ番号\r
- * @throws IllegalStateException マッチしていない\r
- * @throws IndexOutOfBoundsException グループ番号が不正\r
- */\r
- public void setLastMatchedGroupRange(MatchResult result, int groupId)\r
- throws IllegalStateException,\r
- IndexOutOfBoundsException {\r
- this.startPos = result.start(groupId);\r
- this.endPos = result.end(groupId);\r
- return;\r
- }\r
-\r
- /**\r
- * 最後にマッチした範囲全体で設定する。\r
- * @param result 正規表現マッチ結果\r
- * @throws IllegalStateException マッチしていない\r
- */\r
- public void setLastMatchedRange(MatchResult result)\r
- throws IllegalStateException {\r
- this.startPos = result.start();\r
- this.endPos = result.end();\r
- return;\r
- }\r
-\r
- /**\r
- * 開始位置を取得する。\r
- * @return 開始位置\r
- */\r
- public int getStartPos(){\r
- return this.startPos;\r
- }\r
-\r
- /**\r
- * 終了位置を取得する。\r
- * @return 終了位置\r
- */\r
- public int getEndPos(){\r
- return this.endPos;\r
- }\r
-\r
- /**\r
- * 範囲の長さを得る。\r
- * 内容が無効な場合、負の値もありえる。\r
- * @return 長さ\r
- */\r
- public int length(){\r
- int length = this.endPos - this.startPos;\r
- return length;\r
- }\r
-\r
- /**\r
- * 現在の範囲で与えられた文字列を切り出す。\r
- * @param seq 切り出し元文字列\r
- * @return 切り出された文字列\r
- * @throws IndexOutOfBoundsException 範囲が無効\r
- */\r
- public CharSequence sliceSequence(CharSequence seq)\r
- throws IndexOutOfBoundsException{\r
- CharSequence result = seq.subSequence(this.startPos, this.endPos);\r
- return result;\r
- }\r
-\r
- /**\r
- * 範囲指定を無効にする。\r
- */\r
- public void setInvalid(){\r
- this.startPos = -1;\r
- this.endPos = -1;\r
- return;\r
- }\r
-\r
- /**\r
- * 範囲指定が有効か判定する。\r
- * @return 有効であればtrue\r
- */\r
- public boolean isValid(){\r
- if (this.startPos < 0) return false;\r
- else if(this.startPos > this.endPos) return false;\r
- return true;\r
- }\r
-\r
-}\r
+/*
+ * range of string
+ *
+ * License : The MIT License
+ * Copyright(c) 2009 olyutorskii
+ */
+
+package jp.sourceforge.jindolf.parser;
+
+import java.util.regex.MatchResult;
+
+/**
+ * 文字列の範囲を表す。
+ * 範囲は開始位置と終了位置で表される。
+ * 開始位置と終了位置が同じ場合、長さ0の範囲とみなされる。
+ * 開始位置0は文字列の左端を表す。
+ * 開始位置が負の場合、もしくは開始位置より終了位置が小さい場合、
+ * このオブジェクトは無効とみなされる。
+ */
+public class SeqRange{
+
+ private int startPos;
+ private int endPos;
+
+ /**
+ * コンストラクタ。
+ * 開始位置、終了位置ともに無効状態となる。
+ */
+ public SeqRange(){
+ this(-1, -1);
+ return;
+ }
+
+ /**
+ * コンストラクタ。
+ * @param startPos 開始位置
+ * @param endPos 終了位置
+ */
+ public SeqRange(int startPos, int endPos){
+ super();
+ this.startPos = startPos;
+ this.endPos = endPos;
+ return;
+ }
+
+ /**
+ * 開始位置を設定する。
+ * @param startPos 開始位置
+ */
+ public void setStartPos(int startPos){
+ this.startPos = startPos;
+ return;
+ }
+
+ /**
+ * 終了位置を設定する。
+ * @param endPos 終了位置
+ */
+ public void setEndPos(int endPos){
+ this.endPos = endPos;
+ return;
+ }
+
+ /**
+ * 開始位置と終了位置を設定する。
+ * @param startPosition 開始位置
+ * @param endPosition 終了位置
+ */
+ public void setRange(int startPosition, int endPosition){
+ this.startPos = startPosition;
+ this.endPos = endPosition;
+ return;
+ }
+
+ /**
+ * 最後にマッチした前方参照グループの範囲で設定する。
+ * @param result 正規表現マッチ結果
+ * @param groupId グループ番号
+ * @throws IllegalStateException マッチしていない
+ * @throws IndexOutOfBoundsException グループ番号が不正
+ */
+ public void setLastMatchedGroupRange(MatchResult result, int groupId)
+ throws IllegalStateException,
+ IndexOutOfBoundsException {
+ this.startPos = result.start(groupId);
+ this.endPos = result.end(groupId);
+ return;
+ }
+
+ /**
+ * 最後にマッチした範囲全体で設定する。
+ * @param result 正規表現マッチ結果
+ * @throws IllegalStateException マッチしていない
+ */
+ public void setLastMatchedRange(MatchResult result)
+ throws IllegalStateException {
+ this.startPos = result.start();
+ this.endPos = result.end();
+ return;
+ }
+
+ /**
+ * 開始位置を取得する。
+ * @return 開始位置
+ */
+ public int getStartPos(){
+ return this.startPos;
+ }
+
+ /**
+ * 終了位置を取得する。
+ * @return 終了位置
+ */
+ public int getEndPos(){
+ return this.endPos;
+ }
+
+ /**
+ * 範囲の長さを得る。
+ * 内容が無効な場合、負の値もありえる。
+ * @return 長さ
+ */
+ public int length(){
+ int length = this.endPos - this.startPos;
+ return length;
+ }
+
+ /**
+ * 現在の範囲で与えられた文字列を切り出す。
+ * @param seq 切り出し元文字列
+ * @return 切り出された文字列
+ * @throws IndexOutOfBoundsException 範囲が無効
+ */
+ public CharSequence sliceSequence(CharSequence seq)
+ throws IndexOutOfBoundsException{
+ CharSequence result = seq.subSequence(this.startPos, this.endPos);
+ return result;
+ }
+
+ /**
+ * 範囲指定を無効にする。
+ */
+ public void setInvalid(){
+ this.startPos = -1;
+ this.endPos = -1;
+ return;
+ }
+
+ /**
+ * 範囲指定が有効か判定する。
+ * @return 有効であればtrue
+ */
+ public boolean isValid(){
+ if (this.startPos < 0) return false;
+ else if(this.startPos > this.endPos) return false;
+ return true;
+ }
+
+}
-/*\r
- * Shift_JIS encoding utilities\r
- *\r
- * License : The MIT License\r
- * Copyright(c) 2009 olyutorskii\r
- */\r
-\r
-package jp.sourceforge.jindolf.parser;\r
-\r
-import java.nio.charset.Charset;\r
-\r
-/**\r
- * シフトJIS符号化ユーティリティ。\r
- * JIS X0208:1997 準拠。(Windows-31Jではない!)\r
- * @see <a href="http://www.iana.org/assignments/character-sets">\r
- * CHARACTER SETS</a>\r
- * @see <a href="http://ja.wikipedia.org/wiki/Shift_JIS">\r
- * Wikipedia: Shift_JIS</a>\r
- */\r
-public final class ShiftJis{\r
-\r
- /** エンコード名。 */\r
- public static final String ENCODE_NAME = "Shift_JIS";\r
- /** SHift_JIS用Charsetインスタンス。 */\r
- public static final Charset CHARSET = Charset.forName(ENCODE_NAME);\r
- /** char1文字をエンコードした時の最大バイト数。 */\r
- public static final int MAX_BYTES_PER_CHAR = 2;\r
-\r
-\r
- /**\r
- * 隠しコンストラクタ。\r
- */\r
- private ShiftJis(){\r
- super();\r
- return;\r
- }\r
-\r
-\r
- /**\r
- * 任意のバイト値がシフトJISの1バイト目でありうるか否か判定する。\r
- * 文字集合の判定は行わない。\r
- * @param bval バイト値\r
- * @return シフトJISの1バイト目でありうるならtrue\r
- */\r
- public static boolean isShiftJIS1stByte(byte bval){\r
- if( (byte)0x81 <= bval && bval <= (byte)0x9f\r
- || (byte)0xe0 <= bval && bval <= (byte)0xfc){\r
- return true;\r
- }\r
- return false;\r
- }\r
-\r
- /**\r
- * 任意のバイト値がシフトJISの2バイト目でありうるか否か判定する。\r
- * 文字集合の判定は行わない。\r
- * @param bval バイト値\r
- * @return シフトJISの2バイト目でありうるならtrue\r
- */\r
- public static boolean isShiftJIS2ndByte(byte bval){\r
- if( (byte)0x40 <= bval && bval <= (byte)0x7e\r
- || (byte)0x80 <= bval && bval <= (byte)0xfc){\r
- return true;\r
- }\r
- return false;\r
- }\r
-\r
- /**\r
- * 任意のバイト値ペアがシフトJISでありうるか否か判定する。\r
- * 文字集合の判定は行わない。\r
- * @param b1st 第一バイト値\r
- * @param b2nd 第二バイト値\r
- * @return シフトJISならtrue\r
- */\r
- public static boolean isShiftJIS(byte b1st, byte b2nd){\r
- if( ShiftJis.isShiftJIS1stByte(b1st)\r
- && ShiftJis.isShiftJIS2ndByte(b2nd)){\r
- return true;\r
- }\r
- return false;\r
- }\r
-\r
-}\r
+/*
+ * Shift_JIS encoding utilities
+ *
+ * License : The MIT License
+ * Copyright(c) 2009 olyutorskii
+ */
+
+package jp.sourceforge.jindolf.parser;
+
+import java.nio.charset.Charset;
+
+/**
+ * シフトJIS符号化ユーティリティ。
+ * JIS X0208:1997 準拠。(Windows-31Jではない!)
+ * @see <a href="http://www.iana.org/assignments/character-sets">
+ * CHARACTER SETS</a>
+ * @see <a href="http://ja.wikipedia.org/wiki/Shift_JIS">
+ * Wikipedia: Shift_JIS</a>
+ */
+public final class ShiftJis{
+
+ /** エンコード名。 */
+ public static final String ENCODE_NAME = "Shift_JIS";
+ /** SHift_JIS用Charsetインスタンス。 */
+ public static final Charset CHARSET = Charset.forName(ENCODE_NAME);
+ /** char1文字をエンコードした時の最大バイト数。 */
+ public static final int MAX_BYTES_PER_CHAR = 2;
+
+
+ /**
+ * 隠しコンストラクタ。
+ */
+ private ShiftJis(){
+ super();
+ return;
+ }
+
+
+ /**
+ * 任意のバイト値がシフトJISの1バイト目でありうるか否か判定する。
+ * 文字集合の判定は行わない。
+ * @param bval バイト値
+ * @return シフトJISの1バイト目でありうるならtrue
+ */
+ public static boolean isShiftJIS1stByte(byte bval){
+ if( (byte)0x81 <= bval && bval <= (byte)0x9f
+ || (byte)0xe0 <= bval && bval <= (byte)0xfc){
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * 任意のバイト値がシフトJISの2バイト目でありうるか否か判定する。
+ * 文字集合の判定は行わない。
+ * @param bval バイト値
+ * @return シフトJISの2バイト目でありうるならtrue
+ */
+ public static boolean isShiftJIS2ndByte(byte bval){
+ if( (byte)0x40 <= bval && bval <= (byte)0x7e
+ || (byte)0x80 <= bval && bval <= (byte)0xfc){
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * 任意のバイト値ペアがシフトJISでありうるか否か判定する。
+ * 文字集合の判定は行わない。
+ * @param b1st 第一バイト値
+ * @param b2nd 第二バイト値
+ * @return シフトJISならtrue
+ */
+ public static boolean isShiftJIS(byte b1st, byte b2nd){
+ if( ShiftJis.isShiftJIS1stByte(b1st)
+ && ShiftJis.isShiftJIS2ndByte(b2nd)){
+ return true;
+ }
+ return false;
+ }
+
+}
-/*\r
- * stream decoder for Shift_JIS\r
- *\r
- * License : The MIT License\r
- * Copyright(c) 2009 olyutorskii\r
- */\r
-\r
-package jp.sourceforge.jindolf.parser;\r
-\r
-import java.io.IOException;\r
-import java.nio.ByteBuffer;\r
-import java.nio.charset.CoderResult;\r
-\r
-/**\r
- * Shift_JISバイト列のデコードに特化した、{@link StreamDecoder}の派生クラス。\r
- * Java実行系の細かな仕様差異による\r
- * デコードエラー出現パターンゆらぎの正規化も行う。\r
- * 0x5Cが{@literal U+005C}にデコードされるか\r
- * {@literal U+00A5}にデコードされるかはJava実行系の実装依存。\r
- * @see <a href="http://www.iana.org/assignments/character-sets">\r
- * CHARACTER SETS</a>\r
- */\r
-public class SjisDecoder extends StreamDecoder{\r
-\r
- /** 入力バッファに必要な最小サイズ(={@value})。 */\r
- public static final int MIN_INBUFSZ = ShiftJis.MAX_BYTES_PER_CHAR * 2 + 1;\r
-\r
- static{\r
- assert MIN_INBUFSZ <= BYTEBUF_DEFSZ;\r
- }\r
-\r
- /**\r
- * コンストラクタ。\r
- */\r
- public SjisDecoder(){\r
- this(BYTEBUF_DEFSZ, CHARBUF_DEFSZ);\r
- return;\r
- }\r
-\r
- /**\r
- * コンストラクタ。\r
- * @param inbuf_sz 入力バッファサイズ\r
- * @param outbuf_sz 出力バッファサイズ\r
- * @throws IllegalArgumentException バッファサイズが小さすぎる。\r
- */\r
- public SjisDecoder(int inbuf_sz, int outbuf_sz)\r
- throws IllegalArgumentException{\r
- super(ShiftJis.CHARSET.newDecoder(), inbuf_sz, outbuf_sz);\r
- if(inbuf_sz < MIN_INBUFSZ){\r
- throw new IllegalArgumentException();\r
- }\r
- return;\r
- }\r
-\r
- /**\r
- * 1バイトのエラーを2バイトに統合できないか試す。\r
- * @param result デコード異常系\r
- * @return 修正されたデコード異常系。修正がなければ引数と同じものを返す。\r
- * @throws IOException 入力エラー\r
- */\r
- private CoderResult modify1ByteError(CoderResult result)\r
- throws IOException {\r
- ByteBuffer inbuffer = getByteBuffer();\r
-\r
- int currPos;\r
- int nextPos;\r
-\r
- currPos = inbuffer.position();\r
- nextPos = currPos + 1;\r
- if(nextPos >= inbuffer.limit()){\r
- readByteBuffer();\r
- currPos = inbuffer.position();\r
- nextPos = currPos + 1;\r
- }\r
-\r
- // 入力バイト列の最後がこのデコードエラーだった場合。\r
- if(nextPos >= inbuffer.limit()) return result;\r
-\r
- byte curr = inbuffer.get(currPos); // 絶対的get\r
- byte next = inbuffer.get(nextPos);\r
- if( ShiftJis.isShiftJIS(curr, next) ){\r
- return CoderResult.unmappableForLength(2);\r
- }\r
-\r
- return result;\r
- }\r
-\r
- /**\r
- * 2バイトのエラーを1バイトに分割できないか試す。\r
- * ※ バイト列"FF:32" のShift_JISデコードに際して、\r
- * 2バイト長のデコードエラーを返す1.6系実行系が存在する。\r
- * @param result デコード異常系\r
- * @return 修正されたデコード異常系。修正がなければ引数と同じものを返す。\r
- */\r
- private CoderResult modify2ByteError(CoderResult result){\r
- ByteBuffer inbuffer = getByteBuffer();\r
-\r
- int currPos;\r
- int nextPos;\r
-\r
- currPos = inbuffer.position();\r
- nextPos = currPos + 1;\r
-\r
- byte curr = inbuffer.get(currPos); // 絶対的get\r
- byte next = inbuffer.get(nextPos);\r
- if( ! ShiftJis.isShiftJIS(curr, next) ){\r
- return CoderResult.malformedForLength(1);\r
- }\r
-\r
- return result;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- * ライブラリ実装によるシフトJISデコードエラー出現パターンの\r
- * 差異を吸収する。\r
- * @param result {@inheritDoc}\r
- * @return {@inheritDoc}\r
- * @throws IOException {@inheritDoc}\r
- */\r
- @Override\r
- protected int chopErrorSequence(CoderResult result)\r
- throws IOException{\r
- int errorLength = result.length();\r
-\r
- CoderResult newResult;\r
- if(errorLength == 1){\r
- newResult = modify1ByteError(result);\r
- }else if(errorLength == 2){\r
- newResult = modify2ByteError(result);\r
- }else{\r
- assert false;\r
- return -1;\r
- }\r
-\r
- return super.chopErrorSequence(newResult);\r
- }\r
-\r
-}\r
+/*
+ * stream decoder for Shift_JIS
+ *
+ * License : The MIT License
+ * Copyright(c) 2009 olyutorskii
+ */
+
+package jp.sourceforge.jindolf.parser;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.charset.CoderResult;
+
+/**
+ * Shift_JISバイト列のデコードに特化した、{@link StreamDecoder}の派生クラス。
+ * Java実行系の細かな仕様差異による
+ * デコードエラー出現パターンゆらぎの正規化も行う。
+ * 0x5Cが{@literal U+005C}にデコードされるか
+ * {@literal U+00A5}にデコードされるかはJava実行系の実装依存。
+ * @see <a href="http://www.iana.org/assignments/character-sets">
+ * CHARACTER SETS</a>
+ */
+public class SjisDecoder extends StreamDecoder{
+
+ /** 入力バッファに必要な最小サイズ(={@value})。 */
+ public static final int MIN_INBUFSZ = ShiftJis.MAX_BYTES_PER_CHAR * 2 + 1;
+
+ static{
+ assert MIN_INBUFSZ <= BYTEBUF_DEFSZ;
+ }
+
+ /**
+ * コンストラクタ。
+ */
+ public SjisDecoder(){
+ this(BYTEBUF_DEFSZ, CHARBUF_DEFSZ);
+ return;
+ }
+
+ /**
+ * コンストラクタ。
+ * @param inbuf_sz 入力バッファサイズ
+ * @param outbuf_sz 出力バッファサイズ
+ * @throws IllegalArgumentException バッファサイズが小さすぎる。
+ */
+ public SjisDecoder(int inbuf_sz, int outbuf_sz)
+ throws IllegalArgumentException{
+ super(ShiftJis.CHARSET.newDecoder(), inbuf_sz, outbuf_sz);
+ if(inbuf_sz < MIN_INBUFSZ){
+ throw new IllegalArgumentException();
+ }
+ return;
+ }
+
+ /**
+ * 1バイトのエラーを2バイトに統合できないか試す。
+ * @param result デコード異常系
+ * @return 修正されたデコード異常系。修正がなければ引数と同じものを返す。
+ * @throws IOException 入力エラー
+ */
+ private CoderResult modify1ByteError(CoderResult result)
+ throws IOException {
+ ByteBuffer inbuffer = getByteBuffer();
+
+ int currPos;
+ int nextPos;
+
+ currPos = inbuffer.position();
+ nextPos = currPos + 1;
+ if(nextPos >= inbuffer.limit()){
+ readByteBuffer();
+ currPos = inbuffer.position();
+ nextPos = currPos + 1;
+ }
+
+ // 入力バイト列の最後がこのデコードエラーだった場合。
+ if(nextPos >= inbuffer.limit()) return result;
+
+ byte curr = inbuffer.get(currPos); // 絶対的get
+ byte next = inbuffer.get(nextPos);
+ if( ShiftJis.isShiftJIS(curr, next) ){
+ return CoderResult.unmappableForLength(2);
+ }
+
+ return result;
+ }
+
+ /**
+ * 2バイトのエラーを1バイトに分割できないか試す。
+ * ※ バイト列"FF:32" のShift_JISデコードに際して、
+ * 2バイト長のデコードエラーを返す1.6系実行系が存在する。
+ * @param result デコード異常系
+ * @return 修正されたデコード異常系。修正がなければ引数と同じものを返す。
+ */
+ private CoderResult modify2ByteError(CoderResult result){
+ ByteBuffer inbuffer = getByteBuffer();
+
+ int currPos;
+ int nextPos;
+
+ currPos = inbuffer.position();
+ nextPos = currPos + 1;
+
+ byte curr = inbuffer.get(currPos); // 絶対的get
+ byte next = inbuffer.get(nextPos);
+ if( ! ShiftJis.isShiftJIS(curr, next) ){
+ return CoderResult.malformedForLength(1);
+ }
+
+ return result;
+ }
+
+ /**
+ * {@inheritDoc}
+ * ライブラリ実装によるシフトJISデコードエラー出現パターンの
+ * 差異を吸収する。
+ * @param result {@inheritDoc}
+ * @return {@inheritDoc}
+ * @throws IOException {@inheritDoc}
+ */
+ @Override
+ protected int chopErrorSequence(CoderResult result)
+ throws IOException{
+ int errorLength = result.length();
+
+ CoderResult newResult;
+ if(errorLength == 1){
+ newResult = modify1ByteError(result);
+ }else if(errorLength == 2){
+ newResult = modify2ByteError(result);
+ }else{
+ assert false;
+ return -1;
+ }
+
+ return super.chopErrorSequence(newResult);
+ }
+
+}
-/*\r
- * stream decoder\r
- *\r
- * License : The MIT License\r
- * Copyright(c) 2009 olyutorskii\r
- */\r
-\r
-package jp.sourceforge.jindolf.parser;\r
-\r
-import java.io.IOException;\r
-import java.io.InputStream;\r
-import java.nio.ByteBuffer;\r
-import java.nio.CharBuffer;\r
-import java.nio.channels.Channels;\r
-import java.nio.channels.ReadableByteChannel;\r
-import java.nio.charset.CharsetDecoder;\r
-import java.nio.charset.CoderResult;\r
-import java.nio.charset.CodingErrorAction;\r
-import java.util.Arrays;\r
-\r
-/**\r
- * バイトストリームからの文字デコーダ。\r
- * 入力バイトストリームをデコードし、デコード結果およびデコードエラーを\r
- * 文字デコードハンドラ{@link DecodeHandler}に通知する。\r
- * このクラスは、\r
- * デコードエラー詳細を察知できない{@link java.io.InputStreamReader}の\r
- * 代替品として設計された。\r
- * マルチスレッド対応はしていない。\r
- */\r
-public class StreamDecoder{\r
-\r
- /** デフォルト入力バッファサイズ(={@value}bytes)。 */\r
- public static final int BYTEBUF_DEFSZ = 4 * 1024;\r
- /** デフォルト出力バッファサイズ(={@value}chars)。 */\r
- public static final int CHARBUF_DEFSZ = 4 * 1024;\r
-\r
-\r
- private final CharsetDecoder decoder;\r
-\r
- private ReadableByteChannel channel;\r
- private final ByteBuffer byteBuffer;\r
- private final CharBuffer charBuffer;\r
-\r
- private boolean isEndOfInput;\r
- private boolean isFlushing;\r
-\r
- private DecodeHandler decodeHandler;\r
-\r
- // エンコーディングによっては長さに見直しが必要\r
- private byte[] errorData = new byte[4];\r
-\r
-\r
- /**\r
- * コンストラクタ。\r
- * @param decoder デコーダ\r
- */\r
- public StreamDecoder(CharsetDecoder decoder){\r
- this(decoder, BYTEBUF_DEFSZ, CHARBUF_DEFSZ);\r
- return;\r
- }\r
-\r
- /**\r
- * コンストラクタ。\r
- * @param decoder デコーダ\r
- * @param inbuf_sz 入力バッファサイズ\r
- * @param outbuf_sz 出力バッファサイズ\r
- * @throws NullPointerException デコーダにnullを渡した。\r
- * @throws IllegalArgumentException バッファサイズが負。\r
- */\r
- public StreamDecoder(CharsetDecoder decoder,\r
- int inbuf_sz,\r
- int outbuf_sz )\r
- throws NullPointerException,\r
- IllegalArgumentException {\r
- super();\r
-\r
- if(decoder == null) throw new NullPointerException();\r
-\r
- if(inbuf_sz <= 0 || outbuf_sz <= 0){\r
- throw new IllegalArgumentException();\r
- }\r
-\r
- this.decoder = decoder;\r
- this.byteBuffer = ByteBuffer.allocate(inbuf_sz);\r
- this.charBuffer = CharBuffer.allocate(outbuf_sz);\r
- this.channel = null;\r
-\r
- initDecoderImpl();\r
-\r
- return;\r
- }\r
-\r
- /**\r
- * デコーダの初期化下請。\r
- */\r
- private void initDecoderImpl(){\r
- this.byteBuffer.clear().flip();\r
- this.charBuffer.clear();\r
-\r
- this.decoder.onMalformedInput (CodingErrorAction.REPORT);\r
- this.decoder.onUnmappableCharacter(CodingErrorAction.REPORT);\r
- this.decoder.reset();\r
-\r
- this.isEndOfInput = false;\r
- this.isFlushing = false;\r
-\r
- Arrays.fill(this.errorData, (byte)0x00);\r
-\r
- return;\r
- }\r
-\r
- /**\r
- * デコーダの初期化。\r
- */\r
- protected void initDecoder(){\r
- initDecoderImpl();\r
- return;\r
- }\r
-\r
- /**\r
- * 入力バッファを返す。\r
- * @return 入力バッファ\r
- */\r
- protected ByteBuffer getByteBuffer(){\r
- return this.byteBuffer;\r
- }\r
-\r
- /**\r
- * 出力バッファを返す。\r
- * @return 出力バッファ\r
- */\r
- protected CharBuffer getCharBuffer(){\r
- return this.charBuffer;\r
- }\r
-\r
- /**\r
- * デコードハンドラの設定。\r
- * nullオブジェクトを指定しても構わないが、\r
- * その場合パース時に例外を起こす。\r
- * @param decodeHandler デコードハンドラ\r
- */\r
- public void setDecodeHandler(DecodeHandler decodeHandler){\r
- this.decodeHandler = decodeHandler;\r
- return;\r
- }\r
-\r
- /**\r
- * デコードエラー格納配列の再アサイン。\r
- * 配列の内容は保持される。\r
- * 決して縮小することは無い。\r
- * メモ:java.util.Arrays#copyOf()はJRE1.5にない。\r
- * @param size 再アサイン量。バイト長。\r
- */\r
- protected void reassignErrorData(int size){\r
- int oldLength = this.errorData.length;\r
- if(oldLength >= size) return;\r
- int newSize = size;\r
- if(oldLength * 2 > newSize) newSize = oldLength * 2;\r
- byte[] newData = new byte[newSize];\r
- System.arraycopy(this.errorData, 0, newData, 0, oldLength);\r
- this.errorData = newData;\r
- return;\r
- }\r
-\r
- /**\r
- * デコードハンドラに文字列を渡す。\r
- * @throws DecodeException デコードエラー\r
- */\r
- protected void flushContent() throws DecodeException{\r
- if(this.charBuffer.position() <= 0){\r
- return;\r
- }\r
-\r
- this.charBuffer.flip();\r
- this.decodeHandler.charContent(this.charBuffer);\r
- this.charBuffer.clear();\r
-\r
- return;\r
- }\r
-\r
- /**\r
- * デコードハンドラにデコードエラーを渡す。\r
- * @param result デコード結果\r
- * @throws DecodeException デコードエラー\r
- * @throws IOException 入力エラー\r
- */\r
- protected void putDecodeError(CoderResult result)\r
- throws IOException,\r
- DecodeException{\r
- int length = chopErrorSequence(result);\r
- this.decodeHandler.decodingError(this.errorData, 0, length);\r
- return;\r
- }\r
-\r
- /**\r
- * デコードエラーの原因バイト列を抽出する。\r
- * {@link #errorData}の先頭にバイト列が格納され、バイト長が返される。\r
- * @param result デコード結果\r
- * @return 原因バイト列の長さ\r
- * @throws IOException 入力エラー。\r
- * ※このメソッドを継承する場合、必要に応じて先読みをしてもよいし、\r
- * その結果生じたIO例外を投げてもよい。\r
- */\r
- protected int chopErrorSequence(CoderResult result) throws IOException{\r
- int errorLength = result.length();\r
- reassignErrorData(errorLength);\r
- this.byteBuffer.get(this.errorData, 0, errorLength); // 相対get\r
- return errorLength;\r
- }\r
-\r
- /**\r
- * チャンネルからの入力を読み進める。\r
- * 前回の読み残しはバッファ前方に詰め直される。\r
- * @return 入力バイト数。\r
- * @throws java.io.IOException 入出力エラー\r
- */\r
- protected int readByteBuffer() throws IOException{\r
- this.byteBuffer.compact();\r
-\r
- int length = this.channel.read(this.byteBuffer);\r
- if(length <= 0){\r
- this.isEndOfInput = true;\r
- }\r
-\r
- this.byteBuffer.flip();\r
-\r
- return length;\r
- }\r
-\r
- /**\r
- * バイトストリームのデコードを開始する。\r
- * @param istream 入力ストリーム\r
- * @throws IOException 入出力エラー\r
- * @throws DecodeException デコードエラー\r
- */\r
- public void decode(InputStream istream)\r
- throws IOException,\r
- DecodeException {\r
- this.channel = Channels.newChannel(istream);\r
-\r
- try{\r
- decodeChannel();\r
- }finally{\r
- this.channel.close();\r
- this.channel = null;\r
- istream.close();\r
- }\r
-\r
- return;\r
- }\r
-\r
- /**\r
- * 内部チャネルのデコードを開始する。\r
- * @throws IOException 入出力エラー\r
- * @throws DecodeException デコードエラー\r
- */\r
- protected void decodeChannel()\r
- throws IOException,\r
- DecodeException {\r
- initDecoder();\r
-\r
- this.decodeHandler.startDecoding(this.decoder);\r
-\r
- for(;;){\r
- CoderResult result;\r
- if(this.isFlushing){\r
- result = this.decoder.flush(this.charBuffer);\r
- }else{\r
- result = this.decoder.decode(this.byteBuffer,\r
- this.charBuffer,\r
- this.isEndOfInput);\r
- }\r
-\r
- if(result.isError()){\r
- flushContent();\r
- putDecodeError(result);\r
- }else if(result.isOverflow()){ // 出力バッファが一杯\r
- flushContent();\r
- }else if(result.isUnderflow()){ // 入力バッファが空\r
- if( ! this.isEndOfInput ){\r
- readByteBuffer();\r
- continue;\r
- }\r
-\r
- if( ! this.isFlushing ){\r
- this.isFlushing = true;\r
- continue;\r
- }\r
-\r
- flushContent();\r
- break;\r
- }else{\r
- assert false;\r
- }\r
- }\r
-\r
- this.decodeHandler.endDecoding();\r
-\r
- return;\r
- }\r
-\r
-}\r
+/*
+ * stream decoder
+ *
+ * License : The MIT License
+ * Copyright(c) 2009 olyutorskii
+ */
+
+package jp.sourceforge.jindolf.parser;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.channels.Channels;
+import java.nio.channels.ReadableByteChannel;
+import java.nio.charset.CharsetDecoder;
+import java.nio.charset.CoderResult;
+import java.nio.charset.CodingErrorAction;
+import java.util.Arrays;
+
+/**
+ * バイトストリームからの文字デコーダ。
+ * 入力バイトストリームをデコードし、デコード結果およびデコードエラーを
+ * 文字デコードハンドラ{@link DecodeHandler}に通知する。
+ * このクラスは、
+ * デコードエラー詳細を察知できない{@link java.io.InputStreamReader}の
+ * 代替品として設計された。
+ * マルチスレッド対応はしていない。
+ */
+public class StreamDecoder{
+
+ /** デフォルト入力バッファサイズ(={@value}bytes)。 */
+ public static final int BYTEBUF_DEFSZ = 4 * 1024;
+ /** デフォルト出力バッファサイズ(={@value}chars)。 */
+ public static final int CHARBUF_DEFSZ = 4 * 1024;
+
+
+ private final CharsetDecoder decoder;
+
+ private ReadableByteChannel channel;
+ private final ByteBuffer byteBuffer;
+ private final CharBuffer charBuffer;
+
+ private boolean isEndOfInput;
+ private boolean isFlushing;
+
+ private DecodeHandler decodeHandler;
+
+ // エンコーディングによっては長さに見直しが必要
+ private byte[] errorData = new byte[4];
+
+
+ /**
+ * コンストラクタ。
+ * @param decoder デコーダ
+ */
+ public StreamDecoder(CharsetDecoder decoder){
+ this(decoder, BYTEBUF_DEFSZ, CHARBUF_DEFSZ);
+ return;
+ }
+
+ /**
+ * コンストラクタ。
+ * @param decoder デコーダ
+ * @param inbuf_sz 入力バッファサイズ
+ * @param outbuf_sz 出力バッファサイズ
+ * @throws NullPointerException デコーダにnullを渡した。
+ * @throws IllegalArgumentException バッファサイズが負。
+ */
+ public StreamDecoder(CharsetDecoder decoder,
+ int inbuf_sz,
+ int outbuf_sz )
+ throws NullPointerException,
+ IllegalArgumentException {
+ super();
+
+ if(decoder == null) throw new NullPointerException();
+
+ if(inbuf_sz <= 0 || outbuf_sz <= 0){
+ throw new IllegalArgumentException();
+ }
+
+ this.decoder = decoder;
+ this.byteBuffer = ByteBuffer.allocate(inbuf_sz);
+ this.charBuffer = CharBuffer.allocate(outbuf_sz);
+ this.channel = null;
+
+ initDecoderImpl();
+
+ return;
+ }
+
+ /**
+ * デコーダの初期化下請。
+ */
+ private void initDecoderImpl(){
+ this.byteBuffer.clear().flip();
+ this.charBuffer.clear();
+
+ this.decoder.onMalformedInput (CodingErrorAction.REPORT);
+ this.decoder.onUnmappableCharacter(CodingErrorAction.REPORT);
+ this.decoder.reset();
+
+ this.isEndOfInput = false;
+ this.isFlushing = false;
+
+ Arrays.fill(this.errorData, (byte)0x00);
+
+ return;
+ }
+
+ /**
+ * デコーダの初期化。
+ */
+ protected void initDecoder(){
+ initDecoderImpl();
+ return;
+ }
+
+ /**
+ * 入力バッファを返す。
+ * @return 入力バッファ
+ */
+ protected ByteBuffer getByteBuffer(){
+ return this.byteBuffer;
+ }
+
+ /**
+ * 出力バッファを返す。
+ * @return 出力バッファ
+ */
+ protected CharBuffer getCharBuffer(){
+ return this.charBuffer;
+ }
+
+ /**
+ * デコードハンドラの設定。
+ * nullオブジェクトを指定しても構わないが、
+ * その場合パース時に例外を起こす。
+ * @param decodeHandler デコードハンドラ
+ */
+ public void setDecodeHandler(DecodeHandler decodeHandler){
+ this.decodeHandler = decodeHandler;
+ return;
+ }
+
+ /**
+ * デコードエラー格納配列の再アサイン。
+ * 配列の内容は保持される。
+ * 決して縮小することは無い。
+ * メモ:java.util.Arrays#copyOf()はJRE1.5にない。
+ * @param size 再アサイン量。バイト長。
+ */
+ protected void reassignErrorData(int size){
+ int oldLength = this.errorData.length;
+ if(oldLength >= size) return;
+ int newSize = size;
+ if(oldLength * 2 > newSize) newSize = oldLength * 2;
+ byte[] newData = new byte[newSize];
+ System.arraycopy(this.errorData, 0, newData, 0, oldLength);
+ this.errorData = newData;
+ return;
+ }
+
+ /**
+ * デコードハンドラに文字列を渡す。
+ * @throws DecodeException デコードエラー
+ */
+ protected void flushContent() throws DecodeException{
+ if(this.charBuffer.position() <= 0){
+ return;
+ }
+
+ this.charBuffer.flip();
+ this.decodeHandler.charContent(this.charBuffer);
+ this.charBuffer.clear();
+
+ return;
+ }
+
+ /**
+ * デコードハンドラにデコードエラーを渡す。
+ * @param result デコード結果
+ * @throws DecodeException デコードエラー
+ * @throws IOException 入力エラー
+ */
+ protected void putDecodeError(CoderResult result)
+ throws IOException,
+ DecodeException{
+ int length = chopErrorSequence(result);
+ this.decodeHandler.decodingError(this.errorData, 0, length);
+ return;
+ }
+
+ /**
+ * デコードエラーの原因バイト列を抽出する。
+ * {@link #errorData}の先頭にバイト列が格納され、バイト長が返される。
+ * @param result デコード結果
+ * @return 原因バイト列の長さ
+ * @throws IOException 入力エラー。
+ * ※このメソッドを継承する場合、必要に応じて先読みをしてもよいし、
+ * その結果生じたIO例外を投げてもよい。
+ */
+ protected int chopErrorSequence(CoderResult result) throws IOException{
+ int errorLength = result.length();
+ reassignErrorData(errorLength);
+ this.byteBuffer.get(this.errorData, 0, errorLength); // 相対get
+ return errorLength;
+ }
+
+ /**
+ * チャンネルからの入力を読み進める。
+ * 前回の読み残しはバッファ前方に詰め直される。
+ * @return 入力バイト数。
+ * @throws java.io.IOException 入出力エラー
+ */
+ protected int readByteBuffer() throws IOException{
+ this.byteBuffer.compact();
+
+ int length = this.channel.read(this.byteBuffer);
+ if(length <= 0){
+ this.isEndOfInput = true;
+ }
+
+ this.byteBuffer.flip();
+
+ return length;
+ }
+
+ /**
+ * バイトストリームのデコードを開始する。
+ * @param istream 入力ストリーム
+ * @throws IOException 入出力エラー
+ * @throws DecodeException デコードエラー
+ */
+ public void decode(InputStream istream)
+ throws IOException,
+ DecodeException {
+ this.channel = Channels.newChannel(istream);
+
+ try{
+ decodeChannel();
+ }finally{
+ this.channel.close();
+ this.channel = null;
+ istream.close();
+ }
+
+ return;
+ }
+
+ /**
+ * 内部チャネルのデコードを開始する。
+ * @throws IOException 入出力エラー
+ * @throws DecodeException デコードエラー
+ */
+ protected void decodeChannel()
+ throws IOException,
+ DecodeException {
+ initDecoder();
+
+ this.decodeHandler.startDecoding(this.decoder);
+
+ for(;;){
+ CoderResult result;
+ if(this.isFlushing){
+ result = this.decoder.flush(this.charBuffer);
+ }else{
+ result = this.decoder.decode(this.byteBuffer,
+ this.charBuffer,
+ this.isEndOfInput);
+ }
+
+ if(result.isError()){
+ flushContent();
+ putDecodeError(result);
+ }else if(result.isOverflow()){ // 出力バッファが一杯
+ flushContent();
+ }else if(result.isUnderflow()){ // 入力バッファが空
+ if( ! this.isEndOfInput ){
+ readByteBuffer();
+ continue;
+ }
+
+ if( ! this.isFlushing ){
+ this.isFlushing = true;
+ continue;
+ }
+
+ flushContent();
+ break;
+ }else{
+ assert false;
+ }
+ }
+
+ this.decodeHandler.endDecoding();
+
+ return;
+ }
+
+}
-/*\r
- * System event handler\r
- *\r
- * License : The MIT License\r
- * Copyright(c) 2009 olyutorskii\r
- */\r
-\r
-package jp.sourceforge.jindolf.parser;\r
-\r
-import jp.sourceforge.jindolf.corelib.EventFamily;\r
-import jp.sourceforge.jindolf.corelib.GameRole;\r
-import jp.sourceforge.jindolf.corelib.SysEventType;\r
-import jp.sourceforge.jindolf.corelib.Team;\r
-\r
-/**\r
- * システムイベントのパース通知用のハンドラ。\r
- *\r
- * このハンドラの全メソッドはパーサ{@link SysEventParser}から呼び出される。\r
- *\r
- * パーサがシステムイベントを発見すると、まず最初に\r
- * {@link #startSysEvent(EventFamily)}がファミリ種別と共に呼び出される。\r
- * 次にシステムイベントのイベント種別が判明すると、\r
- * {@link #sysEventType(SysEventType)}が呼び出される。\r
- * イベント種別に従い、このハンドラの様々なメソッドが0回以上呼び出される。\r
- * 最後に{@link #endSysEvent()}が呼び出される。\r
- * その後パーサは次のシステムイベントを探し始める。\r
- *\r
- * 一部のメソッドに渡される{@link DecodedContent}文字列オブジェクトは\r
- * mutableである。\r
- * 後々で内容が必要になるならば、ハンドラはSeqRangeで示されたこの内容の\r
- * 必要な箇所をコピーして保存しなければならない。\r
- *\r
- * フラグメントや属性値中の文字参照記号列の解釈はハンドラ側の責務とする。\r
- *\r
- * 各メソッドは、各々の判断で{@link HtmlParseException}をスローする\r
- * ことにより、パース作業を中断させることができる。\r
- */\r
-public interface SysEventHandler{\r
-\r
- /**\r
- * システムイベントのパース開始の通知を受け取る。\r
- * @param eventFamily イベントファミリ種別\r
- * @throws HtmlParseException パースエラー\r
- */\r
- void startSysEvent(EventFamily eventFamily)\r
- throws HtmlParseException;\r
-\r
- /**\r
- * システムイベント種別の通知を受け取る。\r
- * @param type イベント種別\r
- * @throws HtmlParseException パースエラー\r
- */\r
- void sysEventType(SysEventType type)\r
- throws HtmlParseException;\r
-\r
- /**\r
- * システムイベントのパース処理終了の通知を受け取る。\r
- * @throws HtmlParseException パースエラー\r
- */\r
- void endSysEvent()\r
- throws HtmlParseException;\r
-\r
- /**\r
- * ONSTAGEイベントの詳細の通知を受け取る。\r
- * @param content パース対象の文字列\r
- * @param entryNo エントリ番号\r
- * @param avatarRange Avatar名の範囲\r
- * @throws HtmlParseException パースエラー\r
- * @see jp.sourceforge.jindolf.corelib.SysEventType#ONSTAGE\r
- */\r
- void sysEventOnStage(DecodedContent content,\r
- int entryNo,\r
- SeqRange avatarRange )\r
- throws HtmlParseException;\r
-\r
- /**\r
- * OPENROLEイベントの詳細の通知を受け取る。\r
- * 複数回連続して呼ばれる。\r
- * @param role 役職\r
- * @param num 役職の人数\r
- * @throws HtmlParseException パースエラー\r
- * @see jp.sourceforge.jindolf.corelib.SysEventType#OPENROLE\r
- */\r
- void sysEventOpenRole(GameRole role, int num)\r
- throws HtmlParseException;\r
-\r
- /**\r
- * SURVIVORイベントの詳細の通知を受け取る。\r
- * 複数回連続して呼ばれる。\r
- * @param content パース対象の文字列\r
- * @param avatarRange Avatar名の範囲\r
- * @throws HtmlParseException パースエラー\r
- * @see jp.sourceforge.jindolf.corelib.SysEventType#SURVIVOR\r
- */\r
- void sysEventSurvivor(DecodedContent content,\r
- SeqRange avatarRange)\r
- throws HtmlParseException;\r
-\r
- /**\r
- * COUNTINGイベントの詳細の通知を受け取る。\r
- * 複数回連続して呼ばれる。\r
- * 最後の呼び出しで投票元Avatar名の位置情報が負だった場合、\r
- * 投票先Avatar名は処刑が実行されたAvatarを表す。\r
- * @param content パース対象の文字列。\r
- * @param voteByRange 投票元Avatar名の範囲\r
- * @param voteToRange 投票先Avatar名の範囲\r
- * @throws HtmlParseException パースエラー\r
- * @see jp.sourceforge.jindolf.corelib.SysEventType#COUNTING\r
- */\r
- void sysEventCounting(DecodedContent content,\r
- SeqRange voteByRange,\r
- SeqRange voteToRange )\r
- throws HtmlParseException;\r
-\r
- /**\r
- * COUNTING2イベントの詳細の通知を受け取る。※G国のみ\r
- * 複数回連続して呼ばれる。\r
- * @param content パース対象の文字列。\r
- * @param voteByRange 投票元Avatar名の範囲\r
- * @param voteToRange 投票先Avatar名の範囲\r
- * @throws HtmlParseException パースエラー\r
- * @see jp.sourceforge.jindolf.corelib.SysEventType#COUNTING2\r
- */\r
- void sysEventCounting2(DecodedContent content,\r
- SeqRange voteByRange,\r
- SeqRange voteToRange )\r
- throws HtmlParseException;\r
-\r
- /**\r
- * SUDDENDEATHイベントの詳細の通知を受け取る。\r
- * @param content パース対象の文字列\r
- * @param avatarRange Avatar名の範囲\r
- * @throws HtmlParseException パースエラー\r
- * @see jp.sourceforge.jindolf.corelib.SysEventType#SUDDENDEATH\r
- */\r
- void sysEventSuddenDeath(DecodedContent content,\r
- SeqRange avatarRange )\r
- throws HtmlParseException;\r
-\r
- /**\r
- * MURDEREDイベントの詳細の通知を受け取る。\r
- * ハム溶けの時など、連続して複数回呼ばれる事がある。\r
- * @param content パース対象の文字列\r
- * @param avatarRange Avatar名の範囲\r
- * @throws HtmlParseException パースエラー\r
- * @see jp.sourceforge.jindolf.corelib.SysEventType#MURDERED\r
- */\r
- void sysEventMurdered(DecodedContent content,\r
- SeqRange avatarRange )\r
- throws HtmlParseException;\r
-\r
- /**\r
- * PLAYERLISTイベントの詳細の通知を受け取る。\r
- * 複数回連続して呼ばれる。\r
- * @param content パース対象の文字列\r
- * @param avatarRange Avatar名の範囲\r
- * @param anchorRange URLの範囲。無ければ無効。\r
- * @param loginRange IDの範囲\r
- * @param isLiving 生存していればtrue\r
- * @param role 役職\r
- * @throws HtmlParseException パースエラー\r
- * @see jp.sourceforge.jindolf.corelib.SysEventType#PLAYERLIST\r
- */\r
- void sysEventPlayerList(DecodedContent content,\r
- SeqRange avatarRange,\r
- SeqRange anchorRange,\r
- SeqRange loginRange,\r
- boolean isLiving,\r
- GameRole role )\r
- throws HtmlParseException;\r
-\r
- /**\r
- * EXECUTIONイベントの詳細の通知を受け取る。※G国のみ\r
- * 複数回連続して呼ばれる。\r
- * @param content パース対象の文字列。\r
- * @param avatarRange 投票先Avatar名の範囲\r
- * @param votes 得票数。負の値であれば、\r
- * 処刑されたAvatarの通知と見なされる。\r
- * @throws HtmlParseException パースエラー\r
- * @see jp.sourceforge.jindolf.corelib.SysEventType#EXECUTION\r
- */\r
- void sysEventExecution(DecodedContent content,\r
- SeqRange avatarRange,\r
- int votes )\r
- throws HtmlParseException;\r
-\r
- /**\r
- * VANISHイベントの詳細の通知を受け取る。\r
- * @param content パース対象の文字列\r
- * @param avatarRange 失踪したAvatar名の範囲\r
- * @throws HtmlParseException パースエラー\r
- * @see jp.sourceforge.jindolf.corelib.SysEventType#VANISH\r
- */\r
- void sysEventVanish(DecodedContent content,\r
- SeqRange avatarRange )\r
- throws HtmlParseException;\r
-\r
- /**\r
- * CHECKOUTイベントの詳細の通知を受け取る。\r
- * @param content パース対象の文字列\r
- * @param avatarRange 失踪したAvatar名の範囲\r
- * @throws HtmlParseException パースエラー\r
- * @see jp.sourceforge.jindolf.corelib.SysEventType#CHECKOUT\r
- */\r
- void sysEventCheckout(DecodedContent content,\r
- SeqRange avatarRange )\r
- throws HtmlParseException;\r
-\r
- /**\r
- * JUDGEイベントの詳細の通知を受け取る。\r
- * @param content パース対象の文字列。\r
- * @param judgeByRange 占師Avatar名の範囲\r
- * @param judgeToRange 占われたAvatar名の範囲\r
- * @throws HtmlParseException パースエラー\r
- * @see jp.sourceforge.jindolf.corelib.SysEventType#JUDGE\r
- */\r
- void sysEventJudge(DecodedContent content,\r
- SeqRange judgeByRange,\r
- SeqRange judgeToRange )\r
- throws HtmlParseException;\r
-\r
- /**\r
- * GUARDイベントの詳細の通知を受け取る。\r
- * @param content パース対象の文字列。\r
- * @param guardByRange 狩人Avatar名の範囲\r
- * @param guardToRange 護られたAvatar名の範囲\r
- * @throws HtmlParseException パースエラー\r
- * @see jp.sourceforge.jindolf.corelib.SysEventType#GUARD\r
- */\r
- void sysEventGuard(DecodedContent content,\r
- SeqRange guardByRange,\r
- SeqRange guardToRange )\r
- throws HtmlParseException;\r
-\r
- /**\r
- * ASKENTRYイベントの詳細の通知を受け取る。\r
- * @param hour 時間\r
- * @param minute 分\r
- * @param minLimit 最小構成人数\r
- * @param maxLimit 最大定員\r
- * @throws HtmlParseException パースエラー\r
- * @see jp.sourceforge.jindolf.corelib.SysEventType#ASKENTRY\r
- */\r
- void sysEventAskEntry(int hour, int minute,\r
- int minLimit, int maxLimit)\r
- throws HtmlParseException;\r
-\r
- /**\r
- * ASKCOMMITイベントの詳細の通知を受け取る。\r
- * @param hour 時間(24時間制)\r
- * @param minute 分\r
- * @throws HtmlParseException パースエラー\r
- * @see jp.sourceforge.jindolf.corelib.SysEventType#ASKCOMMIT\r
- */\r
- void sysEventAskCommit(int hour, int minute)\r
- throws HtmlParseException;\r
-\r
- /**\r
- * NOCOMMENTイベントの詳細の通知を受け取る。\r
- * 複数回連続して呼ばれる可能性がある。\r
- * @param content パース対象文字列\r
- * @param avatarRange Avatar名の範囲\r
- * @throws HtmlParseException パースエラー\r
- * @see jp.sourceforge.jindolf.corelib.SysEventType#NOCOMMENT\r
- */\r
- void sysEventNoComment(DecodedContent content,\r
- SeqRange avatarRange )\r
- throws HtmlParseException;\r
-\r
- /**\r
- * STAYEPILOGUEイベントの詳細の通知を受け取る。\r
- * @param winner 勝利陣営\r
- * @param hour 時間(24時間制)\r
- * @param minute 分\r
- * @throws HtmlParseException パースエラー\r
- * @see jp.sourceforge.jindolf.corelib.SysEventType#STAYEPILOGUE\r
- */\r
- void sysEventStayEpilogue(Team winner, int hour, int minute)\r
- throws HtmlParseException;\r
-\r
- /**\r
- * イベントの内容(DIV要素)の一般文字列出現の通知を受け取る。\r
- * イベント種別は問わない。\r
- * @param content パース対象文字列\r
- * @param contentRange 内容テキストの範囲\r
- * @throws HtmlParseException パースエラー\r
- */\r
- void sysEventContent(DecodedContent content,\r
- SeqRange contentRange )\r
- throws HtmlParseException;\r
-\r
- /**\r
- * イベントの内容(DIV要素)のBRタグ出現の通知を受け取る。\r
- * イベント種別は問わない。\r
- * @throws HtmlParseException パースエラー\r
- */\r
- void sysEventContentBreak()\r
- throws HtmlParseException;\r
-\r
- /**\r
- * イベントの内容(DIV要素)のAタグ出現の通知を受け取る。\r
- * イベント種別は問わない。\r
- * href属性によるURL記述も通知される。\r
- * @param content パース対象文字列\r
- * @param anchorRange URLの範囲\r
- * @param contentRange 内容テキストの範囲\r
- * @throws HtmlParseException パースエラー\r
- */\r
- void sysEventContentAnchor(DecodedContent content,\r
- SeqRange anchorRange,\r
- SeqRange contentRange )\r
- throws HtmlParseException;\r
-\r
-}\r
+/*
+ * System event handler
+ *
+ * License : The MIT License
+ * Copyright(c) 2009 olyutorskii
+ */
+
+package jp.sourceforge.jindolf.parser;
+
+import jp.sourceforge.jindolf.corelib.EventFamily;
+import jp.sourceforge.jindolf.corelib.GameRole;
+import jp.sourceforge.jindolf.corelib.SysEventType;
+import jp.sourceforge.jindolf.corelib.Team;
+
+/**
+ * システムイベントのパース通知用のハンドラ。
+ *
+ * このハンドラの全メソッドはパーサ{@link SysEventParser}から呼び出される。
+ *
+ * パーサがシステムイベントを発見すると、まず最初に
+ * {@link #startSysEvent(EventFamily)}がファミリ種別と共に呼び出される。
+ * 次にシステムイベントのイベント種別が判明すると、
+ * {@link #sysEventType(SysEventType)}が呼び出される。
+ * イベント種別に従い、このハンドラの様々なメソッドが0回以上呼び出される。
+ * 最後に{@link #endSysEvent()}が呼び出される。
+ * その後パーサは次のシステムイベントを探し始める。
+ *
+ * 一部のメソッドに渡される{@link DecodedContent}文字列オブジェクトは
+ * mutableである。
+ * 後々で内容が必要になるならば、ハンドラはSeqRangeで示されたこの内容の
+ * 必要な箇所をコピーして保存しなければならない。
+ *
+ * フラグメントや属性値中の文字参照記号列の解釈はハンドラ側の責務とする。
+ *
+ * 各メソッドは、各々の判断で{@link HtmlParseException}をスローする
+ * ことにより、パース作業を中断させることができる。
+ */
+public interface SysEventHandler{
+
+ /**
+ * システムイベントのパース開始の通知を受け取る。
+ * @param eventFamily イベントファミリ種別
+ * @throws HtmlParseException パースエラー
+ */
+ void startSysEvent(EventFamily eventFamily)
+ throws HtmlParseException;
+
+ /**
+ * システムイベント種別の通知を受け取る。
+ * @param type イベント種別
+ * @throws HtmlParseException パースエラー
+ */
+ void sysEventType(SysEventType type)
+ throws HtmlParseException;
+
+ /**
+ * システムイベントのパース処理終了の通知を受け取る。
+ * @throws HtmlParseException パースエラー
+ */
+ void endSysEvent()
+ throws HtmlParseException;
+
+ /**
+ * ONSTAGEイベントの詳細の通知を受け取る。
+ * @param content パース対象の文字列
+ * @param entryNo エントリ番号
+ * @param avatarRange Avatar名の範囲
+ * @throws HtmlParseException パースエラー
+ * @see jp.sourceforge.jindolf.corelib.SysEventType#ONSTAGE
+ */
+ void sysEventOnStage(DecodedContent content,
+ int entryNo,
+ SeqRange avatarRange )
+ throws HtmlParseException;
+
+ /**
+ * OPENROLEイベントの詳細の通知を受け取る。
+ * 複数回連続して呼ばれる。
+ * @param role 役職
+ * @param num 役職の人数
+ * @throws HtmlParseException パースエラー
+ * @see jp.sourceforge.jindolf.corelib.SysEventType#OPENROLE
+ */
+ void sysEventOpenRole(GameRole role, int num)
+ throws HtmlParseException;
+
+ /**
+ * SURVIVORイベントの詳細の通知を受け取る。
+ * 複数回連続して呼ばれる。
+ * @param content パース対象の文字列
+ * @param avatarRange Avatar名の範囲
+ * @throws HtmlParseException パースエラー
+ * @see jp.sourceforge.jindolf.corelib.SysEventType#SURVIVOR
+ */
+ void sysEventSurvivor(DecodedContent content,
+ SeqRange avatarRange)
+ throws HtmlParseException;
+
+ /**
+ * COUNTINGイベントの詳細の通知を受け取る。
+ * 複数回連続して呼ばれる。
+ * 最後の呼び出しで投票元Avatar名の位置情報が負だった場合、
+ * 投票先Avatar名は処刑が実行されたAvatarを表す。
+ * @param content パース対象の文字列。
+ * @param voteByRange 投票元Avatar名の範囲
+ * @param voteToRange 投票先Avatar名の範囲
+ * @throws HtmlParseException パースエラー
+ * @see jp.sourceforge.jindolf.corelib.SysEventType#COUNTING
+ */
+ void sysEventCounting(DecodedContent content,
+ SeqRange voteByRange,
+ SeqRange voteToRange )
+ throws HtmlParseException;
+
+ /**
+ * COUNTING2イベントの詳細の通知を受け取る。※G国のみ
+ * 複数回連続して呼ばれる。
+ * @param content パース対象の文字列。
+ * @param voteByRange 投票元Avatar名の範囲
+ * @param voteToRange 投票先Avatar名の範囲
+ * @throws HtmlParseException パースエラー
+ * @see jp.sourceforge.jindolf.corelib.SysEventType#COUNTING2
+ */
+ void sysEventCounting2(DecodedContent content,
+ SeqRange voteByRange,
+ SeqRange voteToRange )
+ throws HtmlParseException;
+
+ /**
+ * SUDDENDEATHイベントの詳細の通知を受け取る。
+ * @param content パース対象の文字列
+ * @param avatarRange Avatar名の範囲
+ * @throws HtmlParseException パースエラー
+ * @see jp.sourceforge.jindolf.corelib.SysEventType#SUDDENDEATH
+ */
+ void sysEventSuddenDeath(DecodedContent content,
+ SeqRange avatarRange )
+ throws HtmlParseException;
+
+ /**
+ * MURDEREDイベントの詳細の通知を受け取る。
+ * ハム溶けの時など、連続して複数回呼ばれる事がある。
+ * @param content パース対象の文字列
+ * @param avatarRange Avatar名の範囲
+ * @throws HtmlParseException パースエラー
+ * @see jp.sourceforge.jindolf.corelib.SysEventType#MURDERED
+ */
+ void sysEventMurdered(DecodedContent content,
+ SeqRange avatarRange )
+ throws HtmlParseException;
+
+ /**
+ * PLAYERLISTイベントの詳細の通知を受け取る。
+ * 複数回連続して呼ばれる。
+ * @param content パース対象の文字列
+ * @param avatarRange Avatar名の範囲
+ * @param anchorRange URLの範囲。無ければ無効。
+ * @param loginRange IDの範囲
+ * @param isLiving 生存していればtrue
+ * @param role 役職
+ * @throws HtmlParseException パースエラー
+ * @see jp.sourceforge.jindolf.corelib.SysEventType#PLAYERLIST
+ */
+ void sysEventPlayerList(DecodedContent content,
+ SeqRange avatarRange,
+ SeqRange anchorRange,
+ SeqRange loginRange,
+ boolean isLiving,
+ GameRole role )
+ throws HtmlParseException;
+
+ /**
+ * EXECUTIONイベントの詳細の通知を受け取る。※G国のみ
+ * 複数回連続して呼ばれる。
+ * @param content パース対象の文字列。
+ * @param avatarRange 投票先Avatar名の範囲
+ * @param votes 得票数。負の値であれば、
+ * 処刑されたAvatarの通知と見なされる。
+ * @throws HtmlParseException パースエラー
+ * @see jp.sourceforge.jindolf.corelib.SysEventType#EXECUTION
+ */
+ void sysEventExecution(DecodedContent content,
+ SeqRange avatarRange,
+ int votes )
+ throws HtmlParseException;
+
+ /**
+ * VANISHイベントの詳細の通知を受け取る。
+ * @param content パース対象の文字列
+ * @param avatarRange 失踪したAvatar名の範囲
+ * @throws HtmlParseException パースエラー
+ * @see jp.sourceforge.jindolf.corelib.SysEventType#VANISH
+ */
+ void sysEventVanish(DecodedContent content,
+ SeqRange avatarRange )
+ throws HtmlParseException;
+
+ /**
+ * CHECKOUTイベントの詳細の通知を受け取る。
+ * @param content パース対象の文字列
+ * @param avatarRange 失踪したAvatar名の範囲
+ * @throws HtmlParseException パースエラー
+ * @see jp.sourceforge.jindolf.corelib.SysEventType#CHECKOUT
+ */
+ void sysEventCheckout(DecodedContent content,
+ SeqRange avatarRange )
+ throws HtmlParseException;
+
+ /**
+ * JUDGEイベントの詳細の通知を受け取る。
+ * @param content パース対象の文字列。
+ * @param judgeByRange 占師Avatar名の範囲
+ * @param judgeToRange 占われたAvatar名の範囲
+ * @throws HtmlParseException パースエラー
+ * @see jp.sourceforge.jindolf.corelib.SysEventType#JUDGE
+ */
+ void sysEventJudge(DecodedContent content,
+ SeqRange judgeByRange,
+ SeqRange judgeToRange )
+ throws HtmlParseException;
+
+ /**
+ * GUARDイベントの詳細の通知を受け取る。
+ * @param content パース対象の文字列。
+ * @param guardByRange 狩人Avatar名の範囲
+ * @param guardToRange 護られたAvatar名の範囲
+ * @throws HtmlParseException パースエラー
+ * @see jp.sourceforge.jindolf.corelib.SysEventType#GUARD
+ */
+ void sysEventGuard(DecodedContent content,
+ SeqRange guardByRange,
+ SeqRange guardToRange )
+ throws HtmlParseException;
+
+ /**
+ * ASKENTRYイベントの詳細の通知を受け取る。
+ * @param hour 時間
+ * @param minute 分
+ * @param minLimit 最小構成人数
+ * @param maxLimit 最大定員
+ * @throws HtmlParseException パースエラー
+ * @see jp.sourceforge.jindolf.corelib.SysEventType#ASKENTRY
+ */
+ void sysEventAskEntry(int hour, int minute,
+ int minLimit, int maxLimit)
+ throws HtmlParseException;
+
+ /**
+ * ASKCOMMITイベントの詳細の通知を受け取る。
+ * @param hour 時間(24時間制)
+ * @param minute 分
+ * @throws HtmlParseException パースエラー
+ * @see jp.sourceforge.jindolf.corelib.SysEventType#ASKCOMMIT
+ */
+ void sysEventAskCommit(int hour, int minute)
+ throws HtmlParseException;
+
+ /**
+ * NOCOMMENTイベントの詳細の通知を受け取る。
+ * 複数回連続して呼ばれる可能性がある。
+ * @param content パース対象文字列
+ * @param avatarRange Avatar名の範囲
+ * @throws HtmlParseException パースエラー
+ * @see jp.sourceforge.jindolf.corelib.SysEventType#NOCOMMENT
+ */
+ void sysEventNoComment(DecodedContent content,
+ SeqRange avatarRange )
+ throws HtmlParseException;
+
+ /**
+ * STAYEPILOGUEイベントの詳細の通知を受け取る。
+ * @param winner 勝利陣営
+ * @param hour 時間(24時間制)
+ * @param minute 分
+ * @throws HtmlParseException パースエラー
+ * @see jp.sourceforge.jindolf.corelib.SysEventType#STAYEPILOGUE
+ */
+ void sysEventStayEpilogue(Team winner, int hour, int minute)
+ throws HtmlParseException;
+
+ /**
+ * イベントの内容(DIV要素)の一般文字列出現の通知を受け取る。
+ * イベント種別は問わない。
+ * @param content パース対象文字列
+ * @param contentRange 内容テキストの範囲
+ * @throws HtmlParseException パースエラー
+ */
+ void sysEventContent(DecodedContent content,
+ SeqRange contentRange )
+ throws HtmlParseException;
+
+ /**
+ * イベントの内容(DIV要素)のBRタグ出現の通知を受け取る。
+ * イベント種別は問わない。
+ * @throws HtmlParseException パースエラー
+ */
+ void sysEventContentBreak()
+ throws HtmlParseException;
+
+ /**
+ * イベントの内容(DIV要素)のAタグ出現の通知を受け取る。
+ * イベント種別は問わない。
+ * href属性によるURL記述も通知される。
+ * @param content パース対象文字列
+ * @param anchorRange URLの範囲
+ * @param contentRange 内容テキストの範囲
+ * @throws HtmlParseException パースエラー
+ */
+ void sysEventContentAnchor(DecodedContent content,
+ SeqRange anchorRange,
+ SeqRange contentRange )
+ throws HtmlParseException;
+
+}
-/*\r
- * System event parser\r
- *\r
- * License : The MIT License\r
- * Copyright(c) 2009 olyutorskii\r
- */\r
-\r
-package jp.sourceforge.jindolf.parser;\r
-\r
-import java.util.regex.Pattern;\r
-import jp.sourceforge.jindolf.corelib.EventFamily;\r
-import jp.sourceforge.jindolf.corelib.GameRole;\r
-import jp.sourceforge.jindolf.corelib.SysEventType;\r
-import jp.sourceforge.jindolf.corelib.Team;\r
-\r
-/**\r
- * 人狼BBSシステムが出力する各種イベント表記のパースを行うパーサ。\r
- * パース進行に従い{@link SysEventHandler}の各種メソッドが呼び出される。\r
- */\r
-public class SysEventParser extends AbstractParser{\r
-\r
- private static final String AVATAR_REGEX =\r
- "[^<、" + SPCHAR + "]+\u0020[^<、。" + SPCHAR + "]+";\r
-\r
- private static final Pattern C_DIV_PATTERN =\r
- compile(SP_I+ "</div>" +SP_I);\r
- private static final Pattern AVATAR_PATTERN =\r
- compile(AVATAR_REGEX);\r
-\r
-\r
- private SysEventHandler sysEventHandler;\r
-\r
- private int pushedRegionStart = -1;\r
- private int pushedRegionEnd = -1;\r
-\r
- private final SeqRange rangepool_1 = new SeqRange();\r
- private final SeqRange rangepool_2 = new SeqRange();\r
- private final SeqRange rangepool_3 = new SeqRange();\r
-\r
- /**\r
- * コンストラクタ。\r
- * @param parent 親パーサ\r
- */\r
- public SysEventParser(ChainedParser parent){\r
- super(parent);\r
- return;\r
- }\r
-\r
- /**\r
- * {@link SysEventHandler}ハンドラを登録する。\r
- * @param sysEventHandler ハンドラ\r
- */\r
- public void setSysEventHandler(SysEventHandler sysEventHandler){\r
- this.sysEventHandler = sysEventHandler;\r
- return;\r
- }\r
-\r
- /**\r
- * Announceメッセージをパースする。\r
- * @throws HtmlParseException パースエラー\r
- */\r
- public void parseAnnounce() throws HtmlParseException{\r
- setContextErrorMessage("Unknown Announce message");\r
-\r
- this.sysEventHandler.startSysEvent(EventFamily.ANNOUNCE);\r
-\r
- int regionStart = regionStart();\r
- int regionEnd = regionEnd();\r
-\r
- boolean result =\r
- probeSimpleAnnounce()\r
- || probeOpenRole()\r
- || probeSurvivor()\r
- || probeMurdered()\r
- || probeOnStage()\r
- || probeSuddenDeath()\r
- || probeCounting()\r
- || probePlayerList()\r
- || probeExecution()\r
- || probeVanish()\r
- || probeCheckout()\r
- ;\r
- if( ! result ){\r
- throw buildParseException();\r
- }\r
-\r
- getMatcher().region(regionStart, regionEnd);\r
- parseContent();\r
-\r
- lookingAtAffirm(C_DIV_PATTERN);\r
- shrinkRegion();\r
-\r
- this.sysEventHandler.endSysEvent();\r
-\r
- return;\r
- }\r
-\r
- private static final Pattern STARTENTRY_PATTERN =\r
- compile(\r
- "昼間は人間のふりをして、夜に正体を現すという人狼。<br />"\r
- +"その人狼が、"\r
- +"この村に紛れ込んでいるという噂が広がった。<br /><br />"\r
- +"村人達は半信半疑ながらも、"\r
- +"村はずれの宿に集められることになった。"\r
- +"<br />");\r
- private static final Pattern STARTMIRROR_PATTERN =\r
- compile(\r
- "さあ、自らの姿を鏡に映してみよう。<br />"\r
- +"そこに映るのはただの村人か、"\r
- +"それとも血に飢えた人狼か。<br /><br />"\r
- +"例え人狼でも、多人数で立ち向かえば怖くはない。<br />"\r
- +"問題は、だれが人狼なのかという事だ。<br />"\r
- +"占い師の能力を持つ人間ならば、それを見破れるだろう。"\r
- +"(?:<br />)?");\r
- private static final Pattern STARTASSAULT_PATTERN =\r
- compile(\r
- "ついに犠牲者が出た。人狼はこの村人達のなかにいる。<br />"\r
- +"しかし、それを見分ける手段はない。<br /><br />"\r
- +"村人達は、疑わしい者を排除するため、"\r
- +"投票を行う事にした。<br />"\r
- +"無実の犠牲者が出るのもやむをえない。"\r
- +"村が全滅するよりは……。<br /><br />"\r
- +"最後まで残るのは村人か、それとも人狼か。"\r
- +"(?:<br />)?");\r
- private static final Pattern NOMURDER_PATTERN =\r
- compile(\r
- "今日は犠牲者がいないようだ。人狼は襲撃に失敗したのだろうか。");\r
- private static final Pattern WINVILLAGE_PATTERN =\r
- compile(\r
- "全ての人狼を退治した……。人狼に怯える日々は去ったのだ!"\r
- +"(?:<br />)?");\r
- private static final Pattern WINWOLF_PATTERN =\r
- compile(\r
- "もう人狼に抵抗できるほど村人は残っていない……。<br />"\r
- +"人狼は残った村人を全て食らい、"\r
- +"別の獲物を求めてこの村を去っていった。"\r
- +"(?:<br />)?");\r
- private static final Pattern WINHAMSTER_PATTERN =\r
- compile(\r
- "全ては終わったかのように見えた。<br />"\r
- +"だが、奴が生き残っていた……。");\r
- private static final Pattern PANIC_PATTERN =\r
- compile("……。");\r
- private static final Pattern SHORTMEMBER_PATTERN =\r
- compile(\r
- "まだ村人達は揃っていないようだ。"\r
- +"(?:<br />)?");\r
-\r
- private static Object[][] simpleRegexToType = {\r
- { STARTENTRY_PATTERN, SysEventType.STARTENTRY },\r
- { STARTMIRROR_PATTERN, SysEventType.STARTMIRROR },\r
- { STARTASSAULT_PATTERN, SysEventType.STARTASSAULT },\r
- { NOMURDER_PATTERN, SysEventType.NOMURDER },\r
- { WINVILLAGE_PATTERN, SysEventType.WINVILLAGE },\r
- { WINWOLF_PATTERN, SysEventType.WINWOLF },\r
- { WINHAMSTER_PATTERN, SysEventType.WINHAMSTER },\r
- { PANIC_PATTERN, SysEventType.PANIC },\r
- { SHORTMEMBER_PATTERN, SysEventType.SHORTMEMBER },\r
- };\r
-\r
- /**\r
- * 文字列が固定されたシンプルなAnnounceメッセージのパースを試みる。\r
- * @return マッチしたらtrue\r
- * @throws HtmlParseException パースエラー\r
- */\r
- private boolean probeSimpleAnnounce() throws HtmlParseException{\r
- pushRegion();\r
-\r
- sweepSpace();\r
-\r
- SysEventType matchedType = null;\r
-\r
- for(Object[] pair : simpleRegexToType){\r
- Pattern pattern = (Pattern)( pair[0] );\r
-\r
- if(lookingAtProbe(pattern)){\r
- shrinkRegion();\r
- matchedType = (SysEventType)( pair[1] );\r
- break;\r
- }\r
- }\r
-\r
- if(matchedType == null){\r
- popRegion();\r
- return false;\r
- }\r
-\r
- this.sysEventHandler.sysEventType(matchedType);\r
-\r
- sweepSpace();\r
-\r
- return true;\r
- }\r
-\r
- private static final Pattern OPENROLE_HEAD_PATTERN =\r
- compile("どうやらこの中には、");\r
- private static final Pattern OPENROLE_NUM_PATTERN =\r
- compile("が([0-9]+)名(?:、)?");\r
- private static final Pattern OPENROLE_TAIL_PATTERN =\r
- compile("いるようだ。");\r
-\r
- /**\r
- * OPENROLEメッセージのパースを試みる。\r
- * @return マッチしたらtrue\r
- * @throws HtmlParseException パースエラー\r
- */\r
- private boolean probeOpenRole() throws HtmlParseException{\r
- pushRegion();\r
-\r
- sweepSpace();\r
-\r
- if( ! lookingAtProbe(OPENROLE_HEAD_PATTERN) ){\r
- popRegion();\r
- return false;\r
- }\r
- shrinkRegion();\r
-\r
- this.sysEventHandler.sysEventType(SysEventType.OPENROLE);\r
-\r
- for(;;){\r
- GameRole role = lookingAtRole();\r
- if(role == null){\r
- if( lookingAtProbe(OPENROLE_TAIL_PATTERN) ){\r
- shrinkRegion();\r
- break;\r
- }\r
- popRegion();\r
- return false;\r
- }\r
- shrinkRegion();\r
-\r
- if( ! lookingAtProbe(OPENROLE_NUM_PATTERN) ){\r
- popRegion();\r
- return false;\r
- }\r
- int num = parseGroupedInt(1);\r
- shrinkRegion();\r
-\r
- this.sysEventHandler.sysEventOpenRole(role, num);\r
- }\r
-\r
- sweepSpace();\r
-\r
- return true;\r
- }\r
-\r
- private static final Pattern SURVIVOR_HEAD_PATTERN =\r
- compile("現在の生存者は、");\r
- private static final Pattern SURVIVOR_PATTERN =\r
- Pattern.compile(\r
- "(" + AVATAR_REGEX + ")"\r
- +"(?:"\r
- +"(?:"\r
- +"、"\r
- +")|(?:"\r
- +"\u0020の\u0020([0-9]+)\u0020名。"\r
- +")"\r
- +")");\r
-\r
- /**\r
- * SURVIVORメッセージのパースを試みる。\r
- * @return マッチしたらtrue\r
- * @throws HtmlParseException パースエラー\r
- */\r
- private boolean probeSurvivor() throws HtmlParseException{\r
- SeqRange avatarRange = this.rangepool_1;\r
-\r
- pushRegion();\r
-\r
- sweepSpace();\r
-\r
- if( ! lookingAtProbe(SURVIVOR_HEAD_PATTERN) ){\r
- popRegion();\r
- return false;\r
- }\r
- shrinkRegion();\r
-\r
- this.sysEventHandler.sysEventType(SysEventType.SURVIVOR);\r
-\r
- int avatarNum = 0;\r
- for(;;){\r
- if( ! lookingAtProbe(SURVIVOR_PATTERN) ){\r
- popRegion();\r
- return false;\r
- }\r
- avatarRange.setLastMatchedGroupRange(getMatcher(), 1);\r
- this.sysEventHandler\r
- .sysEventSurvivor(getContent(), avatarRange);\r
- avatarNum++;\r
- if(isGroupMatched(2)){\r
- int num = parseGroupedInt(2);\r
- shrinkRegion();\r
- if(num != avatarNum){\r
- throw new HtmlParseException(regionStart());\r
- }\r
- break;\r
- }\r
- shrinkRegion();\r
- }\r
-\r
- sweepSpace();\r
-\r
- return true;\r
- }\r
-\r
- private static final Pattern MURDERED_HEAD_PATTERN =\r
- compile("次の日の朝、");\r
- private static final Pattern MURDERED_SW_PATTERN =\r
- compile(\r
- "("\r
- +"\u0020と\u0020"\r
- +")|("\r
- +"\u0020が無残な姿で発見された。"\r
- +"(?:<br />)?" // E国対策\r
- +")"\r
- );\r
-\r
- /**\r
- * MURDEREDメッセージのパースを試みる。\r
- * @return マッチしたらtrue\r
- * @throws HtmlParseException パースエラー\r
- */\r
- private boolean probeMurdered() throws HtmlParseException{\r
- SeqRange avatarRange = this.rangepool_1;\r
- SeqRange avatarRange2 = this.rangepool_2;\r
- avatarRange .setInvalid();\r
- avatarRange2.setInvalid();\r
-\r
- pushRegion();\r
-\r
- sweepSpace();\r
-\r
- if( ! lookingAtProbe(MURDERED_HEAD_PATTERN)){\r
- popRegion();\r
- return false;\r
- }\r
- shrinkRegion();\r
-\r
- this.sysEventHandler.sysEventType(SysEventType.MURDERED);\r
-\r
- for(;;){\r
- if( ! lookingAtProbe(AVATAR_PATTERN)){\r
- popRegion();\r
- return false;\r
- }\r
- if( ! avatarRange.isValid() ){\r
- avatarRange.setLastMatchedRange(getMatcher());\r
- }else if( ! avatarRange2.isValid() ){\r
- avatarRange2.setLastMatchedRange(getMatcher());\r
- }else{\r
- assert false;\r
- throw buildParseException();\r
- }\r
- shrinkRegion();\r
-\r
- if( ! lookingAtProbe(MURDERED_SW_PATTERN)){\r
- popRegion();\r
- return false;\r
- }\r
- if(isGroupMatched(1)){\r
- shrinkRegion();\r
- continue;\r
- }else if(isGroupMatched(2)){\r
- shrinkRegion();\r
- break;\r
- }else{\r
- assert false;\r
- throw buildParseException();\r
- }\r
- }\r
-\r
- this.sysEventHandler\r
- .sysEventMurdered(getContent(), avatarRange);\r
- if(avatarRange2.isValid()){\r
- this.sysEventHandler\r
- .sysEventMurdered(getContent(), avatarRange2);\r
- }\r
-\r
- sweepSpace();\r
-\r
- return true;\r
- }\r
-\r
- private static final Pattern ONSTAGE_NO_PATTERN =\r
- compile("([0-9]+)人目、");\r
- private static final Pattern ONSTAGE_DOT_PATTERN =\r
- compile(\r
- "("\r
- +"(?:" + AVATAR_REGEX + ")"\r
- +"|)" // F1556プロローグ対策\r
- +"。");\r
-\r
- /**\r
- * ONSTAGEメッセージのパースを試みる。\r
- * @return マッチしたらtrue\r
- * @throws HtmlParseException パースエラー\r
- */\r
- private boolean probeOnStage() throws HtmlParseException{\r
- SeqRange avatarRange = this.rangepool_1;\r
-\r
- pushRegion();\r
-\r
- sweepSpace();\r
-\r
- if( ! lookingAtProbe(ONSTAGE_NO_PATTERN) ){\r
- popRegion();\r
- return false;\r
- }\r
- int entryNo = parseGroupedInt(1);\r
- shrinkRegion();\r
-\r
- this.sysEventHandler.sysEventType(SysEventType.ONSTAGE);\r
-\r
- if( ! lookingAtProbe(ONSTAGE_DOT_PATTERN) ){\r
- popRegion();\r
- return false;\r
- }\r
- avatarRange.setLastMatchedGroupRange(getMatcher(), 1);\r
- shrinkRegion();\r
-\r
- this.sysEventHandler\r
- .sysEventOnStage(getContent(), entryNo, avatarRange);\r
-\r
- sweepSpace();\r
-\r
- return true;\r
- }\r
-\r
- private static final Pattern SUDDENDEATH_PATTERN =\r
- compile(\r
- "("\r
- +"(?:" + AVATAR_REGEX + ")"\r
- +"|)" // F681 2d 対策\r
- +"\u0020?は、突然死した。"\r
- );\r
-\r
- /**\r
- * SUDDENDEATHメッセージのパースを試みる。\r
- * @return マッチしたらtrue\r
- * @throws HtmlParseException パースエラー\r
- */\r
- private boolean probeSuddenDeath() throws HtmlParseException{\r
- SeqRange avatarRange = this.rangepool_1;\r
-\r
- pushRegion();\r
-\r
- sweepSpace();\r
-\r
- if( ! lookingAtProbe(SUDDENDEATH_PATTERN)){\r
- popRegion();\r
- return false;\r
- }\r
- avatarRange.setLastMatchedGroupRange(getMatcher(), 1);\r
- shrinkRegion();\r
-\r
- this.sysEventHandler.sysEventType(SysEventType.SUDDENDEATH);\r
- this.sysEventHandler\r
- .sysEventSuddenDeath(getContent(), avatarRange);\r
-\r
- sweepSpace();\r
-\r
- return true;\r
- }\r
-\r
- private static final Pattern COUNTING_PATTERN =\r
- compile(\r
- "(?:"\r
- +"<br />"\r
- +"(" + AVATAR_REGEX + ")"\r
- +"\u0020は村人達の手により処刑された。"\r
- +")|(?:"\r
- +"(" + AVATAR_REGEX + ")"\r
- +"\u0020は\u0020"\r
- +"(" + AVATAR_REGEX + ")"\r
- +"\u0020に投票した。"\r
- +"(?:<br />)?"\r
- +")"\r
- );\r
-\r
- /**\r
- * COUNTINGメッセージのパースを試みる。\r
- * @return マッチしたらtrue\r
- * @throws HtmlParseException パースエラー\r
- */\r
- private boolean probeCounting() throws HtmlParseException{\r
- SeqRange voteByRange = this.rangepool_1;\r
- SeqRange voteToRange = this.rangepool_2;\r
-\r
- pushRegion();\r
-\r
- sweepSpace();\r
-\r
- boolean hasVote = false;\r
- for(;;){\r
- if( ! lookingAtProbe(COUNTING_PATTERN) ){\r
- break; // 処刑なし\r
- }\r
- if(isGroupMatched(1)){\r
- voteByRange.setInvalid();\r
- voteToRange.setLastMatchedGroupRange(getMatcher(), 1);\r
- shrinkRegion();\r
- this.sysEventHandler\r
- .sysEventCounting(getContent(),\r
- voteByRange,\r
- voteToRange );\r
- break;\r
- }else if(isGroupMatched(2)){\r
- if( ! hasVote ){\r
- hasVote = true;\r
- this.sysEventHandler.sysEventType(SysEventType.COUNTING);\r
- }\r
- voteByRange.setLastMatchedGroupRange(getMatcher(), 2);\r
- voteToRange.setLastMatchedGroupRange(getMatcher(), 3);\r
- shrinkRegion();\r
- this.sysEventHandler\r
- .sysEventCounting(getContent(),\r
- voteByRange,\r
- voteToRange );\r
- }else{\r
- assert false;\r
- throw buildParseException();\r
- }\r
- }\r
-\r
- if( ! hasVote ){\r
- popRegion();\r
- return false;\r
- }\r
-\r
- sweepSpace();\r
-\r
- return true;\r
- }\r
-\r
- private static final Pattern COUNTING2_PATTERN =\r
- compile(\r
- "(" + AVATAR_REGEX + ")"\r
- +"\u0020は\u0020"\r
- +"(" + AVATAR_REGEX + ")"\r
- +"\u0020に投票した。"\r
- +"(?:<br />)?"\r
- );\r
-\r
- /**\r
- * COUNTING2メッセージのパースを試みる。\r
- * @return マッチしたらtrue\r
- * @throws HtmlParseException パースエラー\r
- */\r
- private boolean probeCounting2() throws HtmlParseException{\r
- SeqRange voteByRange = this.rangepool_1;\r
- SeqRange voteToRange = this.rangepool_2;\r
-\r
- pushRegion();\r
-\r
- sweepSpace();\r
-\r
- boolean hasVote = false;\r
- for(;;){\r
- if( ! lookingAtProbe(COUNTING2_PATTERN) ){\r
- break;\r
- }\r
- if( ! hasVote ){\r
- hasVote = true;\r
- this.sysEventHandler.sysEventType(SysEventType.COUNTING2);\r
- }\r
- voteByRange.setLastMatchedGroupRange(getMatcher(), 1);\r
- voteToRange.setLastMatchedGroupRange(getMatcher(), 2);\r
- shrinkRegion();\r
- this.sysEventHandler\r
- .sysEventCounting2(getContent(),\r
- voteByRange,\r
- voteToRange );\r
- }\r
-\r
- if( ! hasVote ){\r
- popRegion();\r
- return false;\r
- }\r
-\r
- sweepSpace();\r
-\r
- return true;\r
- }\r
-\r
- private static final Pattern PLAYERID_PATTERN =\r
- compile(\r
- "\u0020\uff08" // 全角開き括弧\r
- +"(?:<a\u0020href=\"([^\"]*)\">)?"\r
- +"([^<]*)"\r
- +"(?:</a>)?"\r
- +"\uff09、" // 全角閉じ括弧\r
- );\r
- private static final Pattern LIVEORDIE_PATTERN =\r
- compile(\r
- "(生存。)|(死亡。)"\r
- );\r
- private static final Pattern PLAYER_DELIM_PATTERN =\r
- compile(\r
- "だった。"\r
- +"(?:<br />)?"\r
- );\r
-\r
- /**\r
- * PLAYERLISTメッセージのパースを試みる。\r
- * @return マッチしたらtrue\r
- * @throws HtmlParseException パースエラー\r
- */\r
- private boolean probePlayerList() throws HtmlParseException{\r
- SeqRange avatarRange = this.rangepool_1;\r
- SeqRange anchorRange = this.rangepool_2;\r
- SeqRange accountRange = this.rangepool_3;\r
-\r
- pushRegion();\r
-\r
- sweepSpace();\r
-\r
- boolean hasPlayerList = false;\r
-\r
- for(;;){\r
- if( ! lookingAtProbe(AVATAR_PATTERN)){\r
- break;\r
- }\r
- avatarRange.setLastMatchedRange(getMatcher());\r
- shrinkRegion();\r
-\r
- if( ! lookingAtProbe(PLAYERID_PATTERN)){\r
- popRegion();\r
- return false;\r
- }\r
- if(isGroupMatched(1)){\r
- anchorRange.setLastMatchedGroupRange(getMatcher(), 1);\r
- }else{\r
- anchorRange.setInvalid();\r
- }\r
- accountRange.setLastMatchedGroupRange(getMatcher(), 2);\r
- shrinkRegion();\r
-\r
- boolean isLiving = false;\r
- if( ! lookingAtProbe(LIVEORDIE_PATTERN)){\r
- popRegion();\r
- return false;\r
- }\r
- if(isGroupMatched(1)){\r
- isLiving = true;\r
- }else if(isGroupMatched(2)){\r
- isLiving = false;\r
- }\r
- shrinkRegion();\r
-\r
- GameRole role = lookingAtRole();\r
- if(role == null){\r
- popRegion();\r
- return false;\r
- }\r
- shrinkRegion();\r
-\r
- if( ! lookingAtProbe(PLAYER_DELIM_PATTERN)){\r
- popRegion();\r
- return false;\r
- }\r
- shrinkRegion();\r
-\r
- if( ! hasPlayerList ){\r
- hasPlayerList = true;\r
- this.sysEventHandler.sysEventType(SysEventType.PLAYERLIST);\r
- }\r
-\r
- this.sysEventHandler\r
- .sysEventPlayerList(getContent(),\r
- avatarRange,\r
- anchorRange,\r
- accountRange,\r
- isLiving,\r
- role );\r
- }\r
-\r
- if( ! hasPlayerList ){\r
- popRegion();\r
- return false;\r
- }\r
-\r
- sweepSpace();\r
-\r
- return true;\r
- }\r
-\r
- private static final Pattern EXECUTION_PATTERN =\r
- compile(\r
- "(?:"\r
- + "(" + AVATAR_REGEX + ")、([0-9]+)票。(?:<br />)?"\r
- +")|(?:"\r
- +"<br />(" + AVATAR_REGEX + ")\u0020は"\r
- +"村人達の手により処刑された。"\r
- +")"\r
- );\r
-\r
- /**\r
- * EXECUTIONメッセージのパースを試みる。\r
- * @return マッチしたらtrue\r
- * @throws HtmlParseException パースエラー\r
- */\r
- private boolean probeExecution() throws HtmlParseException{\r
- SeqRange avatarRange = this.rangepool_1;\r
-\r
- pushRegion();\r
-\r
- sweepSpace();\r
-\r
- boolean hasExecution = false;\r
-\r
- for(;;){\r
- if( ! lookingAtProbe(EXECUTION_PATTERN)){\r
- break;\r
- }\r
-\r
- if( ! hasExecution ){\r
- hasExecution = true;\r
- this.sysEventHandler.sysEventType(SysEventType.EXECUTION);\r
- }\r
-\r
- if(isGroupMatched(1)){\r
- avatarRange.setLastMatchedGroupRange(getMatcher(), 1);\r
- int votes = parseGroupedInt(2);\r
- shrinkRegion();\r
- this.sysEventHandler\r
- .sysEventExecution(getContent(),\r
- avatarRange,\r
- votes );\r
- }else if(isGroupMatched(3)){\r
- avatarRange.setLastMatchedGroupRange(getMatcher(), 3);\r
- shrinkRegion();\r
- this.sysEventHandler\r
- .sysEventExecution(getContent(),\r
- avatarRange,\r
- -1 );\r
- }\r
- }\r
-\r
- if( ! hasExecution ){\r
- popRegion();\r
- return false;\r
- }\r
-\r
- sweepSpace();\r
-\r
- return true;\r
- }\r
-\r
- private static final Pattern VANISH_PATTERN =\r
- compile(\r
- "(?:<br />)*"\r
- +"(" + AVATAR_REGEX + ")"\r
- +"\u0020は、失踪した。"\r
- +"(?:<br />)*"\r
- );\r
-\r
- /**\r
- * VANISHメッセージのパースを試みる。\r
- * @return マッチしたらtrue\r
- * @throws HtmlParseException パースエラー\r
- */\r
- private boolean probeVanish() throws HtmlParseException{\r
- SeqRange avatarRange = this.rangepool_1;\r
-\r
- pushRegion();\r
-\r
- sweepSpace();\r
-\r
- boolean hasVanish = false;\r
-\r
- for(;;){\r
- if( ! lookingAtProbe(VANISH_PATTERN)){\r
- break;\r
- }\r
-\r
- if( ! hasVanish ){\r
- hasVanish = true;\r
- this.sysEventHandler.sysEventType(SysEventType.VANISH);\r
- }\r
- avatarRange.setLastMatchedGroupRange(getMatcher(), 1);\r
-\r
- shrinkRegion();\r
-\r
- this.sysEventHandler\r
- .sysEventVanish(getContent(), avatarRange);\r
- }\r
-\r
- if( ! hasVanish ){\r
- popRegion();\r
- return false;\r
- }\r
-\r
- sweepSpace();\r
-\r
- return true;\r
- }\r
-\r
- private static final Pattern CHECKOUT_PATTERN =\r
- compile(\r
- "(?:<br />)*"\r
- +"(" + AVATAR_REGEX + ")"\r
- +"\u0020は、宿を去った。"\r
- +"(?:<br />)*"\r
- );\r
-\r
- /**\r
- * CHECKOUTメッセージのパースを試みる。\r
- * @return マッチしたらtrue\r
- * @throws HtmlParseException パースエラー\r
- */\r
- private boolean probeCheckout() throws HtmlParseException{\r
- SeqRange avatarRange = this.rangepool_1;\r
-\r
- pushRegion();\r
-\r
- sweepSpace();\r
-\r
- boolean hasCheckout = false;\r
-\r
- for(;;){\r
- if( ! lookingAtProbe(CHECKOUT_PATTERN)){\r
- break;\r
- }\r
-\r
- if( ! hasCheckout ){\r
- hasCheckout = true;\r
- this.sysEventHandler.sysEventType(SysEventType.CHECKOUT);\r
- }\r
- avatarRange.setLastMatchedGroupRange(getMatcher(), 1);\r
-\r
- shrinkRegion();\r
-\r
- this.sysEventHandler\r
- .sysEventCheckout(getContent(), avatarRange);\r
- }\r
-\r
- if( ! hasCheckout ){\r
- popRegion();\r
- return false;\r
- }\r
-\r
- sweepSpace();\r
-\r
- return true;\r
- }\r
-\r
- /**\r
- * Orderメッセージをパースする。\r
- * @throws HtmlParseException パースエラー\r
- */\r
- public void parseOrder() throws HtmlParseException{\r
- setContextErrorMessage("Unknown Order message");\r
-\r
- this.sysEventHandler.startSysEvent(EventFamily.ORDER);\r
-\r
- int regionStart = regionStart();\r
- int regionEnd = regionEnd();\r
-\r
- boolean result =\r
- probeAskEntry()\r
- || probeAskCommit()\r
- || probeNoComment()\r
- || probeStayEpilogue()\r
- || probeGameOver()\r
- ;\r
- if( ! result ){\r
- throw buildParseException();\r
- }\r
-\r
- getMatcher().region(regionStart, regionEnd);\r
- parseContent();\r
-\r
- lookingAtAffirm(C_DIV_PATTERN);\r
- shrinkRegion();\r
-\r
- this.sysEventHandler.endSysEvent();\r
-\r
- return;\r
- }\r
-\r
- private static final Pattern ASKENTRY_PATTERN =\r
- compile(\r
- "演じたいキャラクターを選び、発言してください。<br />"\r
- +"([0-2][0-9]):([0-5][0-9])\u0020に"\r
- +"([0-9]+)名以上がエントリーしていれば進行します。<br />"\r
- +"最大([0-9]+)名まで参加可能です。<br /><br />"\r
- +"※[\u0020]?エントリーは取り消せません。"\r
- +"ルールをよく理解した上でご参加下さい。<br />"\r
- +"(?:※始めての方は、村人希望での参加となります。<br />)?"\r
- +"(?:※希望能力についての発言は控えてください。<br />)?"\r
- );\r
-\r
- /**\r
- * ASKENTRYメッセージのパースを試みる。\r
- * @return マッチしたらtrue\r
- * @throws HtmlParseException パースエラー\r
- */\r
- private boolean probeAskEntry() throws HtmlParseException{\r
- pushRegion();\r
-\r
- sweepSpace();\r
-\r
- if( ! lookingAtProbe(ASKENTRY_PATTERN)){\r
- popRegion();\r
- return false;\r
- }\r
-\r
- int hour = parseGroupedInt(1);\r
- int minute = parseGroupedInt(2);\r
- int minLimit = parseGroupedInt(3);\r
- int maxLimit = parseGroupedInt(4);\r
-\r
- shrinkRegion();\r
-\r
- this.sysEventHandler.sysEventType(SysEventType.ASKENTRY);\r
- this.sysEventHandler\r
- .sysEventAskEntry(hour, minute, minLimit, maxLimit);\r
-\r
- sweepSpace();\r
-\r
- return true;\r
- }\r
-\r
- private static final Pattern ASKCOMMIT_PATTERN =\r
- compile(\r
- "(?:"\r
- +"([0-2][0-9]):([0-5][0-9])\u0020までに、"\r
- +"誰を処刑するべきかの投票先を決定して下さい。<br />"\r
- +"一番票を集めた人物が処刑されます。"\r
- +"同数だった場合はランダムで決定されます。<br /><br />"\r
- +")?"\r
- +"特殊な能力を持つ人は、"\r
- +"([0-2][0-9]):([0-5][0-9])\u0020までに"\r
- +"行動を確定して下さい。<br />"\r
- );\r
-\r
- /**\r
- * ASKCOMMITメッセージのパースを試みる。\r
- * @return マッチしたらtrue\r
- * @throws HtmlParseException パースエラー\r
- */\r
- private boolean probeAskCommit() throws HtmlParseException{\r
- pushRegion();\r
-\r
- sweepSpace();\r
-\r
- if( ! lookingAtProbe(ASKCOMMIT_PATTERN)){\r
- popRegion();\r
- return false;\r
- }\r
-\r
- boolean is1stDay;\r
- if(isGroupMatched(1)){\r
- is1stDay = false;\r
- }else{\r
- is1stDay = true;\r
- }\r
-\r
- int hh1 = parseGroupedInt(1);\r
- int mm1 = parseGroupedInt(2);\r
- int hh2 = parseGroupedInt(3);\r
- int mm2 = parseGroupedInt(4);\r
-\r
- shrinkRegion();\r
-\r
- if( ! is1stDay && (hh1 != hh2 || mm1 != mm2) ){\r
- throw new HtmlParseException(regionStart());\r
- }\r
-\r
- this.sysEventHandler.sysEventType(SysEventType.ASKCOMMIT);\r
- this.sysEventHandler.sysEventAskCommit(hh2, mm2);\r
-\r
- sweepSpace();\r
-\r
- return true;\r
- }\r
-\r
- private static final Pattern NOCOMMENT_HEAD_PATTERN =\r
- compile("本日まだ発言していない者は、");\r
- private static final Pattern NOCOMMENT_AVATAR_PATTERN =\r
- compile(\r
- "(?:"\r
- +"(" + AVATAR_REGEX + ")、"\r
- +")|(?:"\r
- +"以上\u0020([0-9]+)\u0020名。"\r
- +")"\r
- );\r
-\r
- /**\r
- * NOCOMMENTメッセージのパースを試みる。\r
- * @return マッチしたらtrue\r
- * @throws HtmlParseException パースエラー\r
- */\r
- private boolean probeNoComment() throws HtmlParseException{\r
- SeqRange avatarRange = this.rangepool_1;\r
-\r
- pushRegion();\r
-\r
- sweepSpace();\r
-\r
- if( ! lookingAtProbe(NOCOMMENT_HEAD_PATTERN)){\r
- popRegion();\r
- return false;\r
- }\r
- shrinkRegion();\r
-\r
- this.sysEventHandler.sysEventType(SysEventType.NOCOMMENT);\r
-\r
- int avatarNum = 0;\r
- for(;;){\r
- if( ! lookingAtProbe(NOCOMMENT_AVATAR_PATTERN)){\r
- popRegion();\r
- return false;\r
- }\r
-\r
- if(isGroupMatched(1)){\r
- avatarRange.setLastMatchedGroupRange(getMatcher(), 1);\r
- this.sysEventHandler\r
- .sysEventNoComment(getContent(), avatarRange);\r
- shrinkRegion();\r
- avatarNum++;\r
- }else if(isGroupMatched(2)){\r
- int num = parseGroupedInt(2);\r
- shrinkRegion();\r
- if(num != avatarNum){\r
- throw new HtmlParseException(regionStart());\r
- }\r
- break;\r
- }\r
- }\r
-\r
- sweepSpace();\r
-\r
- return true;\r
- }\r
-\r
- private static final Pattern STAYEPILOGUE_PATTERN =\r
- compile(\r
- "(?:(村人)|(人狼)|(ハムスター))側の勝利です!<br />"\r
- +"全てのログとユーザー名を公開します。"\r
- +"([0-2][0-9]):([0-5][0-9])\u0020まで"\r
- +"自由に書き込めますので、"\r
- +"今回の感想などをどうぞ。<br />"\r
- );\r
-\r
- /**\r
- * STAYEPILOGUEメッセージのパースを試みる。\r
- * @return マッチしたらtrue\r
- * @throws HtmlParseException パースエラー\r
- */\r
- private boolean probeStayEpilogue() throws HtmlParseException{\r
- pushRegion();\r
-\r
- sweepSpace();\r
-\r
- if( ! lookingAtProbe(STAYEPILOGUE_PATTERN)){\r
- popRegion();\r
- return false;\r
- }\r
-\r
- Team winner = null;\r
- if(isGroupMatched(1)){\r
- winner = Team.VILLAGE;\r
- }else if(isGroupMatched(2)){\r
- winner = Team.WOLF;\r
- }else if(isGroupMatched(3)){\r
- winner = Team.HAMSTER;\r
- }\r
-\r
- int hour = parseGroupedInt(4);\r
- int minute = parseGroupedInt(5);\r
-\r
- shrinkRegion();\r
-\r
- this.sysEventHandler.sysEventType(SysEventType.STAYEPILOGUE);\r
- this.sysEventHandler.sysEventStayEpilogue(winner, hour, minute);\r
-\r
- sweepSpace();\r
-\r
- return true;\r
- }\r
-\r
- private static final Pattern GAMEOVER_PATTERN =\r
- compile("終了しました。" + "<br />");\r
-\r
- /**\r
- * GAMEOVERメッセージのパースを試みる。\r
- * @return マッチしたらtrue\r
- * @throws HtmlParseException パースエラー\r
- */\r
- private boolean probeGameOver() throws HtmlParseException{\r
- pushRegion();\r
-\r
- sweepSpace();\r
-\r
- if( ! lookingAtProbe(GAMEOVER_PATTERN)){\r
- popRegion();\r
- return false;\r
- }\r
-\r
- shrinkRegion();\r
-\r
- this.sysEventHandler.sysEventType(SysEventType.GAMEOVER);\r
-\r
- sweepSpace();\r
-\r
- return true;\r
- }\r
-\r
- /**\r
- * Extraメッセージをパースする。\r
- * @throws HtmlParseException パースエラー\r
- */\r
- public void parseExtra() throws HtmlParseException{\r
- setContextErrorMessage("Unknown Extra message");\r
-\r
- this.sysEventHandler.startSysEvent(EventFamily.EXTRA);\r
-\r
- int regionStart = regionStart();\r
- int regionEnd = regionEnd();\r
-\r
- boolean result =\r
- probeJudge()\r
- || probeGuard()\r
- || probeCounting2();\r
- if( ! result ){\r
- throw buildParseException();\r
- }\r
-\r
- getMatcher().region(regionStart, regionEnd);\r
- parseContent();\r
-\r
- lookingAtAffirm(C_DIV_PATTERN);\r
- shrinkRegion();\r
-\r
- this.sysEventHandler.endSysEvent();\r
-\r
- return;\r
- }\r
-\r
- private static final Pattern JUDGE_DELIM_PATTERN =\r
- compile("\u0020は、");\r
- private static final Pattern JUDGE_TAIL_PATTERN =\r
- compile("\u0020を占った。");\r
-\r
- /**\r
- * JUDGEメッセージのパースを試みる。\r
- * @return マッチしたらtrue\r
- * @throws HtmlParseException パースエラー\r
- */\r
- private boolean probeJudge() throws HtmlParseException{\r
- SeqRange judgeByRange = this.rangepool_1;\r
- SeqRange judgeToRange = this.rangepool_2;\r
-\r
- pushRegion();\r
-\r
- sweepSpace();\r
-\r
- if( ! lookingAtProbe(AVATAR_PATTERN)){\r
- popRegion();\r
- return false;\r
- }\r
- judgeByRange.setLastMatchedRange(getMatcher());\r
- shrinkRegion();\r
-\r
- if( ! lookingAtProbe(JUDGE_DELIM_PATTERN)){\r
- popRegion();\r
- return false;\r
- }\r
- shrinkRegion();\r
-\r
- if( ! lookingAtProbe(AVATAR_PATTERN)){\r
- popRegion();\r
- return false;\r
- }\r
- judgeToRange.setLastMatchedRange(getMatcher());\r
- shrinkRegion();\r
-\r
- if( ! lookingAtProbe(JUDGE_TAIL_PATTERN)){\r
- popRegion();\r
- return false;\r
- }\r
- shrinkRegion();\r
-\r
- this.sysEventHandler.sysEventType(SysEventType.JUDGE);\r
- this.sysEventHandler\r
- .sysEventJudge(getContent(),\r
- judgeByRange,\r
- judgeToRange );\r
- sweepSpace();\r
-\r
- return true;\r
- }\r
-\r
- private static final Pattern GUARD_DELIM_PATTERN =\r
- compile("\u0020は、");\r
- private static final Pattern GUARD_TAIL_PATTERN =\r
- compile("\u0020を守っている。");\r
-\r
- /**\r
- * GUARDメッセージのパースを試みる。\r
- * @return マッチしたらtrue\r
- * @throws HtmlParseException パースエラー\r
- */\r
- private boolean probeGuard() throws HtmlParseException{\r
- SeqRange guardByRange = this.rangepool_1;\r
- SeqRange guardToRange = this.rangepool_2;\r
-\r
- pushRegion();\r
-\r
- sweepSpace();\r
-\r
- if( ! lookingAtProbe(AVATAR_PATTERN)){\r
- popRegion();\r
- return false;\r
- }\r
- guardByRange.setLastMatchedRange(getMatcher());\r
- shrinkRegion();\r
-\r
- if( ! lookingAtProbe(GUARD_DELIM_PATTERN)){\r
- popRegion();\r
- return false;\r
- }\r
- shrinkRegion();\r
-\r
- if( ! lookingAtProbe(AVATAR_PATTERN)){\r
- popRegion();\r
- return false;\r
- }\r
- guardToRange.setLastMatchedRange(getMatcher());\r
- shrinkRegion();\r
-\r
- if( ! lookingAtProbe(GUARD_TAIL_PATTERN)){\r
- popRegion();\r
- return false;\r
- }\r
- shrinkRegion();\r
-\r
- this.sysEventHandler.sysEventType(SysEventType.GUARD);\r
- this.sysEventHandler.sysEventGuard(getContent(),\r
- guardByRange,\r
- guardToRange );\r
- sweepSpace();\r
-\r
- return true;\r
- }\r
-\r
- private static final Pattern CONTENT_PATTERN =\r
- compile(\r
- "("\r
- +"[^<>\\n\\r]+"\r
- +")|("\r
- +"<br />"\r
- +")|(?:"\r
- +"<a\u0020href=\"([^\"]*)\">([^<>]*)</a>"\r
- +")"\r
- );\r
-\r
- /**\r
- * システムイベントの内容文字列をパースする。\r
- * @throws HtmlParseException パースエラー\r
- */\r
- private void parseContent() throws HtmlParseException{\r
- SeqRange anchorRange = this.rangepool_1;\r
- SeqRange contentRange = this.rangepool_2;\r
-\r
- sweepSpace();\r
-\r
- for(;;){\r
- if( ! lookingAtProbe(CONTENT_PATTERN) ){\r
- break;\r
- }\r
-\r
- if(isGroupMatched(1)){\r
- contentRange.setLastMatchedGroupRange(getMatcher(), 1);\r
- this.sysEventHandler\r
- .sysEventContent(getContent(), contentRange);\r
- }else if(isGroupMatched(2)){\r
- this.sysEventHandler.sysEventContentBreak();\r
- }else if(isGroupMatched(3)){\r
- anchorRange.setLastMatchedGroupRange(getMatcher(), 3);\r
- contentRange.setLastMatchedGroupRange(getMatcher(), 4);\r
- this.sysEventHandler\r
- .sysEventContentAnchor(getContent(),\r
- anchorRange,\r
- contentRange );\r
- }\r
-\r
- shrinkRegion();\r
- }\r
-\r
- sweepSpace();\r
-\r
- return;\r
- }\r
-\r
- /**\r
- * 一時的に現在の検索領域を待避する。\r
- * 待避できるのは1回のみ。複数回スタックはできない。\r
- * @see #popRegion()\r
- */\r
- private void pushRegion(){\r
- this.pushedRegionStart = regionStart();\r
- this.pushedRegionEnd = regionEnd();\r
- return;\r
- }\r
-\r
- /**\r
- * 一時的に待避した検索領域を復活させる。\r
- * @throws IllegalStateException まだ何も待避していない。\r
- * @see #pushRegion()\r
- */\r
- private void popRegion() throws IllegalStateException{\r
- if(this.pushedRegionStart < 0 || this.pushedRegionEnd < 0){\r
- throw new IllegalStateException();\r
- }\r
-\r
- if( this.pushedRegionStart != regionStart()\r
- || this.pushedRegionEnd != regionEnd() ){\r
- getMatcher().region(this.pushedRegionStart, this.pushedRegionEnd);\r
- }\r
-\r
- this.pushedRegionStart = -1;\r
- this.pushedRegionEnd = -1;\r
-\r
- return;\r
- }\r
-\r
-}\r
+/*
+ * System event parser
+ *
+ * License : The MIT License
+ * Copyright(c) 2009 olyutorskii
+ */
+
+package jp.sourceforge.jindolf.parser;
+
+import java.util.regex.Pattern;
+import jp.sourceforge.jindolf.corelib.EventFamily;
+import jp.sourceforge.jindolf.corelib.GameRole;
+import jp.sourceforge.jindolf.corelib.SysEventType;
+import jp.sourceforge.jindolf.corelib.Team;
+
+/**
+ * 人狼BBSシステムが出力する各種イベント表記のパースを行うパーサ。
+ * パース進行に従い{@link SysEventHandler}の各種メソッドが呼び出される。
+ */
+public class SysEventParser extends AbstractParser{
+
+ private static final String AVATAR_REGEX =
+ "[^<、" + SPCHAR + "]+\u0020[^<、。" + SPCHAR + "]+";
+
+ private static final Pattern C_DIV_PATTERN =
+ compile(SP_I+ "</div>" +SP_I);
+ private static final Pattern AVATAR_PATTERN =
+ compile(AVATAR_REGEX);
+
+
+ private SysEventHandler sysEventHandler;
+
+ private int pushedRegionStart = -1;
+ private int pushedRegionEnd = -1;
+
+ private final SeqRange rangepool_1 = new SeqRange();
+ private final SeqRange rangepool_2 = new SeqRange();
+ private final SeqRange rangepool_3 = new SeqRange();
+
+ /**
+ * コンストラクタ。
+ * @param parent 親パーサ
+ */
+ public SysEventParser(ChainedParser parent){
+ super(parent);
+ return;
+ }
+
+ /**
+ * {@link SysEventHandler}ハンドラを登録する。
+ * @param sysEventHandler ハンドラ
+ */
+ public void setSysEventHandler(SysEventHandler sysEventHandler){
+ this.sysEventHandler = sysEventHandler;
+ return;
+ }
+
+ /**
+ * Announceメッセージをパースする。
+ * @throws HtmlParseException パースエラー
+ */
+ public void parseAnnounce() throws HtmlParseException{
+ setContextErrorMessage("Unknown Announce message");
+
+ this.sysEventHandler.startSysEvent(EventFamily.ANNOUNCE);
+
+ int regionStart = regionStart();
+ int regionEnd = regionEnd();
+
+ boolean result =
+ probeSimpleAnnounce()
+ || probeOpenRole()
+ || probeSurvivor()
+ || probeMurdered()
+ || probeOnStage()
+ || probeSuddenDeath()
+ || probeCounting()
+ || probePlayerList()
+ || probeExecution()
+ || probeVanish()
+ || probeCheckout()
+ ;
+ if( ! result ){
+ throw buildParseException();
+ }
+
+ getMatcher().region(regionStart, regionEnd);
+ parseContent();
+
+ lookingAtAffirm(C_DIV_PATTERN);
+ shrinkRegion();
+
+ this.sysEventHandler.endSysEvent();
+
+ return;
+ }
+
+ private static final Pattern STARTENTRY_PATTERN =
+ compile(
+ "昼間は人間のふりをして、夜に正体を現すという人狼。<br />"
+ +"その人狼が、"
+ +"この村に紛れ込んでいるという噂が広がった。<br /><br />"
+ +"村人達は半信半疑ながらも、"
+ +"村はずれの宿に集められることになった。"
+ +"<br />");
+ private static final Pattern STARTMIRROR_PATTERN =
+ compile(
+ "さあ、自らの姿を鏡に映してみよう。<br />"
+ +"そこに映るのはただの村人か、"
+ +"それとも血に飢えた人狼か。<br /><br />"
+ +"例え人狼でも、多人数で立ち向かえば怖くはない。<br />"
+ +"問題は、だれが人狼なのかという事だ。<br />"
+ +"占い師の能力を持つ人間ならば、それを見破れるだろう。"
+ +"(?:<br />)?");
+ private static final Pattern STARTASSAULT_PATTERN =
+ compile(
+ "ついに犠牲者が出た。人狼はこの村人達のなかにいる。<br />"
+ +"しかし、それを見分ける手段はない。<br /><br />"
+ +"村人達は、疑わしい者を排除するため、"
+ +"投票を行う事にした。<br />"
+ +"無実の犠牲者が出るのもやむをえない。"
+ +"村が全滅するよりは……。<br /><br />"
+ +"最後まで残るのは村人か、それとも人狼か。"
+ +"(?:<br />)?");
+ private static final Pattern NOMURDER_PATTERN =
+ compile(
+ "今日は犠牲者がいないようだ。人狼は襲撃に失敗したのだろうか。");
+ private static final Pattern WINVILLAGE_PATTERN =
+ compile(
+ "全ての人狼を退治した……。人狼に怯える日々は去ったのだ!"
+ +"(?:<br />)?");
+ private static final Pattern WINWOLF_PATTERN =
+ compile(
+ "もう人狼に抵抗できるほど村人は残っていない……。<br />"
+ +"人狼は残った村人を全て食らい、"
+ +"別の獲物を求めてこの村を去っていった。"
+ +"(?:<br />)?");
+ private static final Pattern WINHAMSTER_PATTERN =
+ compile(
+ "全ては終わったかのように見えた。<br />"
+ +"だが、奴が生き残っていた……。");
+ private static final Pattern PANIC_PATTERN =
+ compile("……。");
+ private static final Pattern SHORTMEMBER_PATTERN =
+ compile(
+ "まだ村人達は揃っていないようだ。"
+ +"(?:<br />)?");
+
+ private static Object[][] simpleRegexToType = {
+ { STARTENTRY_PATTERN, SysEventType.STARTENTRY },
+ { STARTMIRROR_PATTERN, SysEventType.STARTMIRROR },
+ { STARTASSAULT_PATTERN, SysEventType.STARTASSAULT },
+ { NOMURDER_PATTERN, SysEventType.NOMURDER },
+ { WINVILLAGE_PATTERN, SysEventType.WINVILLAGE },
+ { WINWOLF_PATTERN, SysEventType.WINWOLF },
+ { WINHAMSTER_PATTERN, SysEventType.WINHAMSTER },
+ { PANIC_PATTERN, SysEventType.PANIC },
+ { SHORTMEMBER_PATTERN, SysEventType.SHORTMEMBER },
+ };
+
+ /**
+ * 文字列が固定されたシンプルなAnnounceメッセージのパースを試みる。
+ * @return マッチしたらtrue
+ * @throws HtmlParseException パースエラー
+ */
+ private boolean probeSimpleAnnounce() throws HtmlParseException{
+ pushRegion();
+
+ sweepSpace();
+
+ SysEventType matchedType = null;
+
+ for(Object[] pair : simpleRegexToType){
+ Pattern pattern = (Pattern)( pair[0] );
+
+ if(lookingAtProbe(pattern)){
+ shrinkRegion();
+ matchedType = (SysEventType)( pair[1] );
+ break;
+ }
+ }
+
+ if(matchedType == null){
+ popRegion();
+ return false;
+ }
+
+ this.sysEventHandler.sysEventType(matchedType);
+
+ sweepSpace();
+
+ return true;
+ }
+
+ private static final Pattern OPENROLE_HEAD_PATTERN =
+ compile("どうやらこの中には、");
+ private static final Pattern OPENROLE_NUM_PATTERN =
+ compile("が([0-9]+)名(?:、)?");
+ private static final Pattern OPENROLE_TAIL_PATTERN =
+ compile("いるようだ。");
+
+ /**
+ * OPENROLEメッセージのパースを試みる。
+ * @return マッチしたらtrue
+ * @throws HtmlParseException パースエラー
+ */
+ private boolean probeOpenRole() throws HtmlParseException{
+ pushRegion();
+
+ sweepSpace();
+
+ if( ! lookingAtProbe(OPENROLE_HEAD_PATTERN) ){
+ popRegion();
+ return false;
+ }
+ shrinkRegion();
+
+ this.sysEventHandler.sysEventType(SysEventType.OPENROLE);
+
+ for(;;){
+ GameRole role = lookingAtRole();
+ if(role == null){
+ if( lookingAtProbe(OPENROLE_TAIL_PATTERN) ){
+ shrinkRegion();
+ break;
+ }
+ popRegion();
+ return false;
+ }
+ shrinkRegion();
+
+ if( ! lookingAtProbe(OPENROLE_NUM_PATTERN) ){
+ popRegion();
+ return false;
+ }
+ int num = parseGroupedInt(1);
+ shrinkRegion();
+
+ this.sysEventHandler.sysEventOpenRole(role, num);
+ }
+
+ sweepSpace();
+
+ return true;
+ }
+
+ private static final Pattern SURVIVOR_HEAD_PATTERN =
+ compile("現在の生存者は、");
+ private static final Pattern SURVIVOR_PATTERN =
+ Pattern.compile(
+ "(" + AVATAR_REGEX + ")"
+ +"(?:"
+ +"(?:"
+ +"、"
+ +")|(?:"
+ +"\u0020の\u0020([0-9]+)\u0020名。"
+ +")"
+ +")");
+
+ /**
+ * SURVIVORメッセージのパースを試みる。
+ * @return マッチしたらtrue
+ * @throws HtmlParseException パースエラー
+ */
+ private boolean probeSurvivor() throws HtmlParseException{
+ SeqRange avatarRange = this.rangepool_1;
+
+ pushRegion();
+
+ sweepSpace();
+
+ if( ! lookingAtProbe(SURVIVOR_HEAD_PATTERN) ){
+ popRegion();
+ return false;
+ }
+ shrinkRegion();
+
+ this.sysEventHandler.sysEventType(SysEventType.SURVIVOR);
+
+ int avatarNum = 0;
+ for(;;){
+ if( ! lookingAtProbe(SURVIVOR_PATTERN) ){
+ popRegion();
+ return false;
+ }
+ avatarRange.setLastMatchedGroupRange(getMatcher(), 1);
+ this.sysEventHandler
+ .sysEventSurvivor(getContent(), avatarRange);
+ avatarNum++;
+ if(isGroupMatched(2)){
+ int num = parseGroupedInt(2);
+ shrinkRegion();
+ if(num != avatarNum){
+ throw new HtmlParseException(regionStart());
+ }
+ break;
+ }
+ shrinkRegion();
+ }
+
+ sweepSpace();
+
+ return true;
+ }
+
+ private static final Pattern MURDERED_HEAD_PATTERN =
+ compile("次の日の朝、");
+ private static final Pattern MURDERED_SW_PATTERN =
+ compile(
+ "("
+ +"\u0020と\u0020"
+ +")|("
+ +"\u0020が無残な姿で発見された。"
+ +"(?:<br />)?" // E国対策
+ +")"
+ );
+
+ /**
+ * MURDEREDメッセージのパースを試みる。
+ * @return マッチしたらtrue
+ * @throws HtmlParseException パースエラー
+ */
+ private boolean probeMurdered() throws HtmlParseException{
+ SeqRange avatarRange = this.rangepool_1;
+ SeqRange avatarRange2 = this.rangepool_2;
+ avatarRange .setInvalid();
+ avatarRange2.setInvalid();
+
+ pushRegion();
+
+ sweepSpace();
+
+ if( ! lookingAtProbe(MURDERED_HEAD_PATTERN)){
+ popRegion();
+ return false;
+ }
+ shrinkRegion();
+
+ this.sysEventHandler.sysEventType(SysEventType.MURDERED);
+
+ for(;;){
+ if( ! lookingAtProbe(AVATAR_PATTERN)){
+ popRegion();
+ return false;
+ }
+ if( ! avatarRange.isValid() ){
+ avatarRange.setLastMatchedRange(getMatcher());
+ }else if( ! avatarRange2.isValid() ){
+ avatarRange2.setLastMatchedRange(getMatcher());
+ }else{
+ assert false;
+ throw buildParseException();
+ }
+ shrinkRegion();
+
+ if( ! lookingAtProbe(MURDERED_SW_PATTERN)){
+ popRegion();
+ return false;
+ }
+ if(isGroupMatched(1)){
+ shrinkRegion();
+ continue;
+ }else if(isGroupMatched(2)){
+ shrinkRegion();
+ break;
+ }else{
+ assert false;
+ throw buildParseException();
+ }
+ }
+
+ this.sysEventHandler
+ .sysEventMurdered(getContent(), avatarRange);
+ if(avatarRange2.isValid()){
+ this.sysEventHandler
+ .sysEventMurdered(getContent(), avatarRange2);
+ }
+
+ sweepSpace();
+
+ return true;
+ }
+
+ private static final Pattern ONSTAGE_NO_PATTERN =
+ compile("([0-9]+)人目、");
+ private static final Pattern ONSTAGE_DOT_PATTERN =
+ compile(
+ "("
+ +"(?:" + AVATAR_REGEX + ")"
+ +"|)" // F1556プロローグ対策
+ +"。");
+
+ /**
+ * ONSTAGEメッセージのパースを試みる。
+ * @return マッチしたらtrue
+ * @throws HtmlParseException パースエラー
+ */
+ private boolean probeOnStage() throws HtmlParseException{
+ SeqRange avatarRange = this.rangepool_1;
+
+ pushRegion();
+
+ sweepSpace();
+
+ if( ! lookingAtProbe(ONSTAGE_NO_PATTERN) ){
+ popRegion();
+ return false;
+ }
+ int entryNo = parseGroupedInt(1);
+ shrinkRegion();
+
+ this.sysEventHandler.sysEventType(SysEventType.ONSTAGE);
+
+ if( ! lookingAtProbe(ONSTAGE_DOT_PATTERN) ){
+ popRegion();
+ return false;
+ }
+ avatarRange.setLastMatchedGroupRange(getMatcher(), 1);
+ shrinkRegion();
+
+ this.sysEventHandler
+ .sysEventOnStage(getContent(), entryNo, avatarRange);
+
+ sweepSpace();
+
+ return true;
+ }
+
+ private static final Pattern SUDDENDEATH_PATTERN =
+ compile(
+ "("
+ +"(?:" + AVATAR_REGEX + ")"
+ +"|)" // F681 2d 対策
+ +"\u0020?は、突然死した。"
+ );
+
+ /**
+ * SUDDENDEATHメッセージのパースを試みる。
+ * @return マッチしたらtrue
+ * @throws HtmlParseException パースエラー
+ */
+ private boolean probeSuddenDeath() throws HtmlParseException{
+ SeqRange avatarRange = this.rangepool_1;
+
+ pushRegion();
+
+ sweepSpace();
+
+ if( ! lookingAtProbe(SUDDENDEATH_PATTERN)){
+ popRegion();
+ return false;
+ }
+ avatarRange.setLastMatchedGroupRange(getMatcher(), 1);
+ shrinkRegion();
+
+ this.sysEventHandler.sysEventType(SysEventType.SUDDENDEATH);
+ this.sysEventHandler
+ .sysEventSuddenDeath(getContent(), avatarRange);
+
+ sweepSpace();
+
+ return true;
+ }
+
+ private static final Pattern COUNTING_PATTERN =
+ compile(
+ "(?:"
+ +"<br />"
+ +"(" + AVATAR_REGEX + ")"
+ +"\u0020は村人達の手により処刑された。"
+ +")|(?:"
+ +"(" + AVATAR_REGEX + ")"
+ +"\u0020は\u0020"
+ +"(" + AVATAR_REGEX + ")"
+ +"\u0020に投票した。"
+ +"(?:<br />)?"
+ +")"
+ );
+
+ /**
+ * COUNTINGメッセージのパースを試みる。
+ * @return マッチしたらtrue
+ * @throws HtmlParseException パースエラー
+ */
+ private boolean probeCounting() throws HtmlParseException{
+ SeqRange voteByRange = this.rangepool_1;
+ SeqRange voteToRange = this.rangepool_2;
+
+ pushRegion();
+
+ sweepSpace();
+
+ boolean hasVote = false;
+ for(;;){
+ if( ! lookingAtProbe(COUNTING_PATTERN) ){
+ break; // 処刑なし
+ }
+ if(isGroupMatched(1)){
+ voteByRange.setInvalid();
+ voteToRange.setLastMatchedGroupRange(getMatcher(), 1);
+ shrinkRegion();
+ this.sysEventHandler
+ .sysEventCounting(getContent(),
+ voteByRange,
+ voteToRange );
+ break;
+ }else if(isGroupMatched(2)){
+ if( ! hasVote ){
+ hasVote = true;
+ this.sysEventHandler.sysEventType(SysEventType.COUNTING);
+ }
+ voteByRange.setLastMatchedGroupRange(getMatcher(), 2);
+ voteToRange.setLastMatchedGroupRange(getMatcher(), 3);
+ shrinkRegion();
+ this.sysEventHandler
+ .sysEventCounting(getContent(),
+ voteByRange,
+ voteToRange );
+ }else{
+ assert false;
+ throw buildParseException();
+ }
+ }
+
+ if( ! hasVote ){
+ popRegion();
+ return false;
+ }
+
+ sweepSpace();
+
+ return true;
+ }
+
+ private static final Pattern COUNTING2_PATTERN =
+ compile(
+ "(" + AVATAR_REGEX + ")"
+ +"\u0020は\u0020"
+ +"(" + AVATAR_REGEX + ")"
+ +"\u0020に投票した。"
+ +"(?:<br />)?"
+ );
+
+ /**
+ * COUNTING2メッセージのパースを試みる。
+ * @return マッチしたらtrue
+ * @throws HtmlParseException パースエラー
+ */
+ private boolean probeCounting2() throws HtmlParseException{
+ SeqRange voteByRange = this.rangepool_1;
+ SeqRange voteToRange = this.rangepool_2;
+
+ pushRegion();
+
+ sweepSpace();
+
+ boolean hasVote = false;
+ for(;;){
+ if( ! lookingAtProbe(COUNTING2_PATTERN) ){
+ break;
+ }
+ if( ! hasVote ){
+ hasVote = true;
+ this.sysEventHandler.sysEventType(SysEventType.COUNTING2);
+ }
+ voteByRange.setLastMatchedGroupRange(getMatcher(), 1);
+ voteToRange.setLastMatchedGroupRange(getMatcher(), 2);
+ shrinkRegion();
+ this.sysEventHandler
+ .sysEventCounting2(getContent(),
+ voteByRange,
+ voteToRange );
+ }
+
+ if( ! hasVote ){
+ popRegion();
+ return false;
+ }
+
+ sweepSpace();
+
+ return true;
+ }
+
+ private static final Pattern PLAYERID_PATTERN =
+ compile(
+ "\u0020\uff08" // 全角開き括弧
+ +"(?:<a\u0020href=\"([^\"]*)\">)?"
+ +"([^<]*)"
+ +"(?:</a>)?"
+ +"\uff09、" // 全角閉じ括弧
+ );
+ private static final Pattern LIVEORDIE_PATTERN =
+ compile(
+ "(生存。)|(死亡。)"
+ );
+ private static final Pattern PLAYER_DELIM_PATTERN =
+ compile(
+ "だった。"
+ +"(?:<br />)?"
+ );
+
+ /**
+ * PLAYERLISTメッセージのパースを試みる。
+ * @return マッチしたらtrue
+ * @throws HtmlParseException パースエラー
+ */
+ private boolean probePlayerList() throws HtmlParseException{
+ SeqRange avatarRange = this.rangepool_1;
+ SeqRange anchorRange = this.rangepool_2;
+ SeqRange accountRange = this.rangepool_3;
+
+ pushRegion();
+
+ sweepSpace();
+
+ boolean hasPlayerList = false;
+
+ for(;;){
+ if( ! lookingAtProbe(AVATAR_PATTERN)){
+ break;
+ }
+ avatarRange.setLastMatchedRange(getMatcher());
+ shrinkRegion();
+
+ if( ! lookingAtProbe(PLAYERID_PATTERN)){
+ popRegion();
+ return false;
+ }
+ if(isGroupMatched(1)){
+ anchorRange.setLastMatchedGroupRange(getMatcher(), 1);
+ }else{
+ anchorRange.setInvalid();
+ }
+ accountRange.setLastMatchedGroupRange(getMatcher(), 2);
+ shrinkRegion();
+
+ boolean isLiving = false;
+ if( ! lookingAtProbe(LIVEORDIE_PATTERN)){
+ popRegion();
+ return false;
+ }
+ if(isGroupMatched(1)){
+ isLiving = true;
+ }else if(isGroupMatched(2)){
+ isLiving = false;
+ }
+ shrinkRegion();
+
+ GameRole role = lookingAtRole();
+ if(role == null){
+ popRegion();
+ return false;
+ }
+ shrinkRegion();
+
+ if( ! lookingAtProbe(PLAYER_DELIM_PATTERN)){
+ popRegion();
+ return false;
+ }
+ shrinkRegion();
+
+ if( ! hasPlayerList ){
+ hasPlayerList = true;
+ this.sysEventHandler.sysEventType(SysEventType.PLAYERLIST);
+ }
+
+ this.sysEventHandler
+ .sysEventPlayerList(getContent(),
+ avatarRange,
+ anchorRange,
+ accountRange,
+ isLiving,
+ role );
+ }
+
+ if( ! hasPlayerList ){
+ popRegion();
+ return false;
+ }
+
+ sweepSpace();
+
+ return true;
+ }
+
+ private static final Pattern EXECUTION_PATTERN =
+ compile(
+ "(?:"
+ + "(" + AVATAR_REGEX + ")、([0-9]+)票。(?:<br />)?"
+ +")|(?:"
+ +"<br />(" + AVATAR_REGEX + ")\u0020は"
+ +"村人達の手により処刑された。"
+ +")"
+ );
+
+ /**
+ * EXECUTIONメッセージのパースを試みる。
+ * @return マッチしたらtrue
+ * @throws HtmlParseException パースエラー
+ */
+ private boolean probeExecution() throws HtmlParseException{
+ SeqRange avatarRange = this.rangepool_1;
+
+ pushRegion();
+
+ sweepSpace();
+
+ boolean hasExecution = false;
+
+ for(;;){
+ if( ! lookingAtProbe(EXECUTION_PATTERN)){
+ break;
+ }
+
+ if( ! hasExecution ){
+ hasExecution = true;
+ this.sysEventHandler.sysEventType(SysEventType.EXECUTION);
+ }
+
+ if(isGroupMatched(1)){
+ avatarRange.setLastMatchedGroupRange(getMatcher(), 1);
+ int votes = parseGroupedInt(2);
+ shrinkRegion();
+ this.sysEventHandler
+ .sysEventExecution(getContent(),
+ avatarRange,
+ votes );
+ }else if(isGroupMatched(3)){
+ avatarRange.setLastMatchedGroupRange(getMatcher(), 3);
+ shrinkRegion();
+ this.sysEventHandler
+ .sysEventExecution(getContent(),
+ avatarRange,
+ -1 );
+ }
+ }
+
+ if( ! hasExecution ){
+ popRegion();
+ return false;
+ }
+
+ sweepSpace();
+
+ return true;
+ }
+
+ private static final Pattern VANISH_PATTERN =
+ compile(
+ "(?:<br />)*"
+ +"(" + AVATAR_REGEX + ")"
+ +"\u0020は、失踪した。"
+ +"(?:<br />)*"
+ );
+
+ /**
+ * VANISHメッセージのパースを試みる。
+ * @return マッチしたらtrue
+ * @throws HtmlParseException パースエラー
+ */
+ private boolean probeVanish() throws HtmlParseException{
+ SeqRange avatarRange = this.rangepool_1;
+
+ pushRegion();
+
+ sweepSpace();
+
+ boolean hasVanish = false;
+
+ for(;;){
+ if( ! lookingAtProbe(VANISH_PATTERN)){
+ break;
+ }
+
+ if( ! hasVanish ){
+ hasVanish = true;
+ this.sysEventHandler.sysEventType(SysEventType.VANISH);
+ }
+ avatarRange.setLastMatchedGroupRange(getMatcher(), 1);
+
+ shrinkRegion();
+
+ this.sysEventHandler
+ .sysEventVanish(getContent(), avatarRange);
+ }
+
+ if( ! hasVanish ){
+ popRegion();
+ return false;
+ }
+
+ sweepSpace();
+
+ return true;
+ }
+
+ private static final Pattern CHECKOUT_PATTERN =
+ compile(
+ "(?:<br />)*"
+ +"(" + AVATAR_REGEX + ")"
+ +"\u0020は、宿を去った。"
+ +"(?:<br />)*"
+ );
+
+ /**
+ * CHECKOUTメッセージのパースを試みる。
+ * @return マッチしたらtrue
+ * @throws HtmlParseException パースエラー
+ */
+ private boolean probeCheckout() throws HtmlParseException{
+ SeqRange avatarRange = this.rangepool_1;
+
+ pushRegion();
+
+ sweepSpace();
+
+ boolean hasCheckout = false;
+
+ for(;;){
+ if( ! lookingAtProbe(CHECKOUT_PATTERN)){
+ break;
+ }
+
+ if( ! hasCheckout ){
+ hasCheckout = true;
+ this.sysEventHandler.sysEventType(SysEventType.CHECKOUT);
+ }
+ avatarRange.setLastMatchedGroupRange(getMatcher(), 1);
+
+ shrinkRegion();
+
+ this.sysEventHandler
+ .sysEventCheckout(getContent(), avatarRange);
+ }
+
+ if( ! hasCheckout ){
+ popRegion();
+ return false;
+ }
+
+ sweepSpace();
+
+ return true;
+ }
+
+ /**
+ * Orderメッセージをパースする。
+ * @throws HtmlParseException パースエラー
+ */
+ public void parseOrder() throws HtmlParseException{
+ setContextErrorMessage("Unknown Order message");
+
+ this.sysEventHandler.startSysEvent(EventFamily.ORDER);
+
+ int regionStart = regionStart();
+ int regionEnd = regionEnd();
+
+ boolean result =
+ probeAskEntry()
+ || probeAskCommit()
+ || probeNoComment()
+ || probeStayEpilogue()
+ || probeGameOver()
+ ;
+ if( ! result ){
+ throw buildParseException();
+ }
+
+ getMatcher().region(regionStart, regionEnd);
+ parseContent();
+
+ lookingAtAffirm(C_DIV_PATTERN);
+ shrinkRegion();
+
+ this.sysEventHandler.endSysEvent();
+
+ return;
+ }
+
+ private static final Pattern ASKENTRY_PATTERN =
+ compile(
+ "演じたいキャラクターを選び、発言してください。<br />"
+ +"([0-2][0-9]):([0-5][0-9])\u0020に"
+ +"([0-9]+)名以上がエントリーしていれば進行します。<br />"
+ +"最大([0-9]+)名まで参加可能です。<br /><br />"
+ +"※[\u0020]?エントリーは取り消せません。"
+ +"ルールをよく理解した上でご参加下さい。<br />"
+ +"(?:※始めての方は、村人希望での参加となります。<br />)?"
+ +"(?:※希望能力についての発言は控えてください。<br />)?"
+ );
+
+ /**
+ * ASKENTRYメッセージのパースを試みる。
+ * @return マッチしたらtrue
+ * @throws HtmlParseException パースエラー
+ */
+ private boolean probeAskEntry() throws HtmlParseException{
+ pushRegion();
+
+ sweepSpace();
+
+ if( ! lookingAtProbe(ASKENTRY_PATTERN)){
+ popRegion();
+ return false;
+ }
+
+ int hour = parseGroupedInt(1);
+ int minute = parseGroupedInt(2);
+ int minLimit = parseGroupedInt(3);
+ int maxLimit = parseGroupedInt(4);
+
+ shrinkRegion();
+
+ this.sysEventHandler.sysEventType(SysEventType.ASKENTRY);
+ this.sysEventHandler
+ .sysEventAskEntry(hour, minute, minLimit, maxLimit);
+
+ sweepSpace();
+
+ return true;
+ }
+
+ private static final Pattern ASKCOMMIT_PATTERN =
+ compile(
+ "(?:"
+ +"([0-2][0-9]):([0-5][0-9])\u0020までに、"
+ +"誰を処刑するべきかの投票先を決定して下さい。<br />"
+ +"一番票を集めた人物が処刑されます。"
+ +"同数だった場合はランダムで決定されます。<br /><br />"
+ +")?"
+ +"特殊な能力を持つ人は、"
+ +"([0-2][0-9]):([0-5][0-9])\u0020までに"
+ +"行動を確定して下さい。<br />"
+ );
+
+ /**
+ * ASKCOMMITメッセージのパースを試みる。
+ * @return マッチしたらtrue
+ * @throws HtmlParseException パースエラー
+ */
+ private boolean probeAskCommit() throws HtmlParseException{
+ pushRegion();
+
+ sweepSpace();
+
+ if( ! lookingAtProbe(ASKCOMMIT_PATTERN)){
+ popRegion();
+ return false;
+ }
+
+ boolean is1stDay;
+ if(isGroupMatched(1)){
+ is1stDay = false;
+ }else{
+ is1stDay = true;
+ }
+
+ int hh1 = parseGroupedInt(1);
+ int mm1 = parseGroupedInt(2);
+ int hh2 = parseGroupedInt(3);
+ int mm2 = parseGroupedInt(4);
+
+ shrinkRegion();
+
+ if( ! is1stDay && (hh1 != hh2 || mm1 != mm2) ){
+ throw new HtmlParseException(regionStart());
+ }
+
+ this.sysEventHandler.sysEventType(SysEventType.ASKCOMMIT);
+ this.sysEventHandler.sysEventAskCommit(hh2, mm2);
+
+ sweepSpace();
+
+ return true;
+ }
+
+ private static final Pattern NOCOMMENT_HEAD_PATTERN =
+ compile("本日まだ発言していない者は、");
+ private static final Pattern NOCOMMENT_AVATAR_PATTERN =
+ compile(
+ "(?:"
+ +"(" + AVATAR_REGEX + ")、"
+ +")|(?:"
+ +"以上\u0020([0-9]+)\u0020名。"
+ +")"
+ );
+
+ /**
+ * NOCOMMENTメッセージのパースを試みる。
+ * @return マッチしたらtrue
+ * @throws HtmlParseException パースエラー
+ */
+ private boolean probeNoComment() throws HtmlParseException{
+ SeqRange avatarRange = this.rangepool_1;
+
+ pushRegion();
+
+ sweepSpace();
+
+ if( ! lookingAtProbe(NOCOMMENT_HEAD_PATTERN)){
+ popRegion();
+ return false;
+ }
+ shrinkRegion();
+
+ this.sysEventHandler.sysEventType(SysEventType.NOCOMMENT);
+
+ int avatarNum = 0;
+ for(;;){
+ if( ! lookingAtProbe(NOCOMMENT_AVATAR_PATTERN)){
+ popRegion();
+ return false;
+ }
+
+ if(isGroupMatched(1)){
+ avatarRange.setLastMatchedGroupRange(getMatcher(), 1);
+ this.sysEventHandler
+ .sysEventNoComment(getContent(), avatarRange);
+ shrinkRegion();
+ avatarNum++;
+ }else if(isGroupMatched(2)){
+ int num = parseGroupedInt(2);
+ shrinkRegion();
+ if(num != avatarNum){
+ throw new HtmlParseException(regionStart());
+ }
+ break;
+ }
+ }
+
+ sweepSpace();
+
+ return true;
+ }
+
+ private static final Pattern STAYEPILOGUE_PATTERN =
+ compile(
+ "(?:(村人)|(人狼)|(ハムスター))側の勝利です!<br />"
+ +"全てのログとユーザー名を公開します。"
+ +"([0-2][0-9]):([0-5][0-9])\u0020まで"
+ +"自由に書き込めますので、"
+ +"今回の感想などをどうぞ。<br />"
+ );
+
+ /**
+ * STAYEPILOGUEメッセージのパースを試みる。
+ * @return マッチしたらtrue
+ * @throws HtmlParseException パースエラー
+ */
+ private boolean probeStayEpilogue() throws HtmlParseException{
+ pushRegion();
+
+ sweepSpace();
+
+ if( ! lookingAtProbe(STAYEPILOGUE_PATTERN)){
+ popRegion();
+ return false;
+ }
+
+ Team winner = null;
+ if(isGroupMatched(1)){
+ winner = Team.VILLAGE;
+ }else if(isGroupMatched(2)){
+ winner = Team.WOLF;
+ }else if(isGroupMatched(3)){
+ winner = Team.HAMSTER;
+ }
+
+ int hour = parseGroupedInt(4);
+ int minute = parseGroupedInt(5);
+
+ shrinkRegion();
+
+ this.sysEventHandler.sysEventType(SysEventType.STAYEPILOGUE);
+ this.sysEventHandler.sysEventStayEpilogue(winner, hour, minute);
+
+ sweepSpace();
+
+ return true;
+ }
+
+ private static final Pattern GAMEOVER_PATTERN =
+ compile("終了しました。" + "<br />");
+
+ /**
+ * GAMEOVERメッセージのパースを試みる。
+ * @return マッチしたらtrue
+ * @throws HtmlParseException パースエラー
+ */
+ private boolean probeGameOver() throws HtmlParseException{
+ pushRegion();
+
+ sweepSpace();
+
+ if( ! lookingAtProbe(GAMEOVER_PATTERN)){
+ popRegion();
+ return false;
+ }
+
+ shrinkRegion();
+
+ this.sysEventHandler.sysEventType(SysEventType.GAMEOVER);
+
+ sweepSpace();
+
+ return true;
+ }
+
+ /**
+ * Extraメッセージをパースする。
+ * @throws HtmlParseException パースエラー
+ */
+ public void parseExtra() throws HtmlParseException{
+ setContextErrorMessage("Unknown Extra message");
+
+ this.sysEventHandler.startSysEvent(EventFamily.EXTRA);
+
+ int regionStart = regionStart();
+ int regionEnd = regionEnd();
+
+ boolean result =
+ probeJudge()
+ || probeGuard()
+ || probeCounting2();
+ if( ! result ){
+ throw buildParseException();
+ }
+
+ getMatcher().region(regionStart, regionEnd);
+ parseContent();
+
+ lookingAtAffirm(C_DIV_PATTERN);
+ shrinkRegion();
+
+ this.sysEventHandler.endSysEvent();
+
+ return;
+ }
+
+ private static final Pattern JUDGE_DELIM_PATTERN =
+ compile("\u0020は、");
+ private static final Pattern JUDGE_TAIL_PATTERN =
+ compile("\u0020を占った。");
+
+ /**
+ * JUDGEメッセージのパースを試みる。
+ * @return マッチしたらtrue
+ * @throws HtmlParseException パースエラー
+ */
+ private boolean probeJudge() throws HtmlParseException{
+ SeqRange judgeByRange = this.rangepool_1;
+ SeqRange judgeToRange = this.rangepool_2;
+
+ pushRegion();
+
+ sweepSpace();
+
+ if( ! lookingAtProbe(AVATAR_PATTERN)){
+ popRegion();
+ return false;
+ }
+ judgeByRange.setLastMatchedRange(getMatcher());
+ shrinkRegion();
+
+ if( ! lookingAtProbe(JUDGE_DELIM_PATTERN)){
+ popRegion();
+ return false;
+ }
+ shrinkRegion();
+
+ if( ! lookingAtProbe(AVATAR_PATTERN)){
+ popRegion();
+ return false;
+ }
+ judgeToRange.setLastMatchedRange(getMatcher());
+ shrinkRegion();
+
+ if( ! lookingAtProbe(JUDGE_TAIL_PATTERN)){
+ popRegion();
+ return false;
+ }
+ shrinkRegion();
+
+ this.sysEventHandler.sysEventType(SysEventType.JUDGE);
+ this.sysEventHandler
+ .sysEventJudge(getContent(),
+ judgeByRange,
+ judgeToRange );
+ sweepSpace();
+
+ return true;
+ }
+
+ private static final Pattern GUARD_DELIM_PATTERN =
+ compile("\u0020は、");
+ private static final Pattern GUARD_TAIL_PATTERN =
+ compile("\u0020を守っている。");
+
+ /**
+ * GUARDメッセージのパースを試みる。
+ * @return マッチしたらtrue
+ * @throws HtmlParseException パースエラー
+ */
+ private boolean probeGuard() throws HtmlParseException{
+ SeqRange guardByRange = this.rangepool_1;
+ SeqRange guardToRange = this.rangepool_2;
+
+ pushRegion();
+
+ sweepSpace();
+
+ if( ! lookingAtProbe(AVATAR_PATTERN)){
+ popRegion();
+ return false;
+ }
+ guardByRange.setLastMatchedRange(getMatcher());
+ shrinkRegion();
+
+ if( ! lookingAtProbe(GUARD_DELIM_PATTERN)){
+ popRegion();
+ return false;
+ }
+ shrinkRegion();
+
+ if( ! lookingAtProbe(AVATAR_PATTERN)){
+ popRegion();
+ return false;
+ }
+ guardToRange.setLastMatchedRange(getMatcher());
+ shrinkRegion();
+
+ if( ! lookingAtProbe(GUARD_TAIL_PATTERN)){
+ popRegion();
+ return false;
+ }
+ shrinkRegion();
+
+ this.sysEventHandler.sysEventType(SysEventType.GUARD);
+ this.sysEventHandler.sysEventGuard(getContent(),
+ guardByRange,
+ guardToRange );
+ sweepSpace();
+
+ return true;
+ }
+
+ private static final Pattern CONTENT_PATTERN =
+ compile(
+ "("
+ +"[^<>\\n\\r]+"
+ +")|("
+ +"<br />"
+ +")|(?:"
+ +"<a\u0020href=\"([^\"]*)\">([^<>]*)</a>"
+ +")"
+ );
+
+ /**
+ * システムイベントの内容文字列をパースする。
+ * @throws HtmlParseException パースエラー
+ */
+ private void parseContent() throws HtmlParseException{
+ SeqRange anchorRange = this.rangepool_1;
+ SeqRange contentRange = this.rangepool_2;
+
+ sweepSpace();
+
+ for(;;){
+ if( ! lookingAtProbe(CONTENT_PATTERN) ){
+ break;
+ }
+
+ if(isGroupMatched(1)){
+ contentRange.setLastMatchedGroupRange(getMatcher(), 1);
+ this.sysEventHandler
+ .sysEventContent(getContent(), contentRange);
+ }else if(isGroupMatched(2)){
+ this.sysEventHandler.sysEventContentBreak();
+ }else if(isGroupMatched(3)){
+ anchorRange.setLastMatchedGroupRange(getMatcher(), 3);
+ contentRange.setLastMatchedGroupRange(getMatcher(), 4);
+ this.sysEventHandler
+ .sysEventContentAnchor(getContent(),
+ anchorRange,
+ contentRange );
+ }
+
+ shrinkRegion();
+ }
+
+ sweepSpace();
+
+ return;
+ }
+
+ /**
+ * 一時的に現在の検索領域を待避する。
+ * 待避できるのは1回のみ。複数回スタックはできない。
+ * @see #popRegion()
+ */
+ private void pushRegion(){
+ this.pushedRegionStart = regionStart();
+ this.pushedRegionEnd = regionEnd();
+ return;
+ }
+
+ /**
+ * 一時的に待避した検索領域を復活させる。
+ * @throws IllegalStateException まだ何も待避していない。
+ * @see #pushRegion()
+ */
+ private void popRegion() throws IllegalStateException{
+ if(this.pushedRegionStart < 0 || this.pushedRegionEnd < 0){
+ throw new IllegalStateException();
+ }
+
+ if( this.pushedRegionStart != regionStart()
+ || this.pushedRegionEnd != regionEnd() ){
+ getMatcher().region(this.pushedRegionStart, this.pushedRegionEnd);
+ }
+
+ this.pushedRegionStart = -1;
+ this.pushedRegionEnd = -1;
+
+ return;
+ }
+
+}
-/*\r
- * handler for parse talk-part\r
- *\r
- * License : The MIT License\r
- * Copyright(c) 2009 olyutorskii\r
- */\r
-\r
-package jp.sourceforge.jindolf.parser;\r
-\r
-import jp.sourceforge.jindolf.corelib.TalkType;\r
-\r
-/**\r
- * 人狼BBSの発言部XHTML断片をパースするためのハンドラ。\r
- *\r
- * このハンドラの全メソッドはパーサ{@link HtmlParser}から呼び出される。\r
- *\r
- * パーサが発言箇所を発見すると、まず最初に\r
- * {@link #startTalk()}が呼び出される。\r
- * 発言内容に従い、このハンドラの様々なメソッドが0回以上呼び出される。\r
- * 最後に{@link #endTalk()}が呼び出される。\r
- * その後パーサは次の発言を探し始める。\r
- *\r
- * 一部のメソッドに渡される{@link DecodedContent}文字列オブジェクトは\r
- * mutableである。\r
- * 後々で内容が必要になるならば、ハンドラはSeqRangeで示されたこの内容の\r
- * 必要な箇所をコピーして保存しなければならない。\r
- *\r
- * フラグメントや属性値中の文字参照記号列の解釈はハンドラ側の責務とする。\r
- *\r
- * 各メソッドは、各々の判断で{@link HtmlParseException}をスローする\r
- * ことにより、パース作業を中断させることができる。\r
- */\r
-public interface TalkHandler{\r
-\r
- /**\r
- * 発言部パース開始の通知を受け取る。\r
- * @throws HtmlParseException パースエラー\r
- */\r
- void startTalk()\r
- throws HtmlParseException;\r
-\r
- /**\r
- * 発言部パース終了の通知を受け取る。\r
- * @throws HtmlParseException パースエラー\r
- */\r
- void endTalk()\r
- throws HtmlParseException;\r
-\r
- /**\r
- * 白発言番号を受け取る。※G国only。\r
- * 負の値が渡ってきた場合は白発言でないので無視してよい。\r
- * @param talkNo 白発言番号\r
- * @throws HtmlParseException パースエラー\r
- */\r
- void talkNo(int talkNo)\r
- throws HtmlParseException;\r
-\r
- /**\r
- * 発言部ID(Aタグのname属性)の通知を受け取る。\r
- * @param content パース対象文字列\r
- * @param idRange IDの範囲\r
- * @throws HtmlParseException パースエラー\r
- */\r
- void talkId(DecodedContent content, SeqRange idRange)\r
- throws HtmlParseException;\r
-\r
- /**\r
- * 発言したAvatar名の通知を受け取る。\r
- * @param content パース対象文字列\r
- * @param avatarRange Avatar名の範囲\r
- * @throws HtmlParseException パースエラー\r
- */\r
- void talkAvatar(DecodedContent content, SeqRange avatarRange)\r
- throws HtmlParseException;\r
-\r
- /**\r
- * 発言時刻の通知を受け取る。\r
- * @param hour 時間(24時間制)\r
- * @param minute 分\r
- * @throws HtmlParseException パースエラー\r
- */\r
- void talkTime(int hour, int minute)\r
- throws HtmlParseException;\r
-\r
- /**\r
- * 発言者の顔アイコンURLの通知を受け取る。\r
- * @param content パース対象文字列\r
- * @param urlRange URLの範囲。\r
- * @throws HtmlParseException パースエラー\r
- */\r
- void talkIconUrl(DecodedContent content, SeqRange urlRange)\r
- throws HtmlParseException;\r
-\r
- /**\r
- * 発言種別の通知を受け取る。\r
- * @param type 発言種別\r
- * @throws HtmlParseException パースエラー\r
- */\r
- void talkType(TalkType type)\r
- throws HtmlParseException;\r
-\r
- /**\r
- * 発言テキスト内容の通知を受け取る。\r
- * 1発言のパース中に複数回呼ばれる事もありうる。\r
- * @param content パース対象文字列\r
- * @param textRange テキストの範囲\r
- * @throws HtmlParseException パースエラー\r
- */\r
- void talkText(DecodedContent content, SeqRange textRange)\r
- throws HtmlParseException;\r
-\r
- /**\r
- * 発言テキスト内のBRタグ出現の通知を受け取る。\r
- * 1発言のパース中に複数回呼ばれる事もありうる。\r
- * @throws HtmlParseException パースエラー\r
- */\r
- void talkBreak()\r
- throws HtmlParseException;\r
-\r
-}\r
+/*
+ * handler for parse talk-part
+ *
+ * License : The MIT License
+ * Copyright(c) 2009 olyutorskii
+ */
+
+package jp.sourceforge.jindolf.parser;
+
+import jp.sourceforge.jindolf.corelib.TalkType;
+
+/**
+ * 人狼BBSの発言部XHTML断片をパースするためのハンドラ。
+ *
+ * このハンドラの全メソッドはパーサ{@link HtmlParser}から呼び出される。
+ *
+ * パーサが発言箇所を発見すると、まず最初に
+ * {@link #startTalk()}が呼び出される。
+ * 発言内容に従い、このハンドラの様々なメソッドが0回以上呼び出される。
+ * 最後に{@link #endTalk()}が呼び出される。
+ * その後パーサは次の発言を探し始める。
+ *
+ * 一部のメソッドに渡される{@link DecodedContent}文字列オブジェクトは
+ * mutableである。
+ * 後々で内容が必要になるならば、ハンドラはSeqRangeで示されたこの内容の
+ * 必要な箇所をコピーして保存しなければならない。
+ *
+ * フラグメントや属性値中の文字参照記号列の解釈はハンドラ側の責務とする。
+ *
+ * 各メソッドは、各々の判断で{@link HtmlParseException}をスローする
+ * ことにより、パース作業を中断させることができる。
+ */
+public interface TalkHandler{
+
+ /**
+ * 発言部パース開始の通知を受け取る。
+ * @throws HtmlParseException パースエラー
+ */
+ void startTalk()
+ throws HtmlParseException;
+
+ /**
+ * 発言部パース終了の通知を受け取る。
+ * @throws HtmlParseException パースエラー
+ */
+ void endTalk()
+ throws HtmlParseException;
+
+ /**
+ * 白発言番号を受け取る。※G国only。
+ * 負の値が渡ってきた場合は白発言でないので無視してよい。
+ * @param talkNo 白発言番号
+ * @throws HtmlParseException パースエラー
+ */
+ void talkNo(int talkNo)
+ throws HtmlParseException;
+
+ /**
+ * 発言部ID(Aタグのname属性)の通知を受け取る。
+ * @param content パース対象文字列
+ * @param idRange IDの範囲
+ * @throws HtmlParseException パースエラー
+ */
+ void talkId(DecodedContent content, SeqRange idRange)
+ throws HtmlParseException;
+
+ /**
+ * 発言したAvatar名の通知を受け取る。
+ * @param content パース対象文字列
+ * @param avatarRange Avatar名の範囲
+ * @throws HtmlParseException パースエラー
+ */
+ void talkAvatar(DecodedContent content, SeqRange avatarRange)
+ throws HtmlParseException;
+
+ /**
+ * 発言時刻の通知を受け取る。
+ * @param hour 時間(24時間制)
+ * @param minute 分
+ * @throws HtmlParseException パースエラー
+ */
+ void talkTime(int hour, int minute)
+ throws HtmlParseException;
+
+ /**
+ * 発言者の顔アイコンURLの通知を受け取る。
+ * @param content パース対象文字列
+ * @param urlRange URLの範囲。
+ * @throws HtmlParseException パースエラー
+ */
+ void talkIconUrl(DecodedContent content, SeqRange urlRange)
+ throws HtmlParseException;
+
+ /**
+ * 発言種別の通知を受け取る。
+ * @param type 発言種別
+ * @throws HtmlParseException パースエラー
+ */
+ void talkType(TalkType type)
+ throws HtmlParseException;
+
+ /**
+ * 発言テキスト内容の通知を受け取る。
+ * 1発言のパース中に複数回呼ばれる事もありうる。
+ * @param content パース対象文字列
+ * @param textRange テキストの範囲
+ * @throws HtmlParseException パースエラー
+ */
+ void talkText(DecodedContent content, SeqRange textRange)
+ throws HtmlParseException;
+
+ /**
+ * 発言テキスト内のBRタグ出現の通知を受け取る。
+ * 1発言のパース中に複数回呼ばれる事もありうる。
+ * @throws HtmlParseException パースエラー
+ */
+ void talkBreak()
+ throws HtmlParseException;
+
+}
-/*\r
- * talk-part parser\r
- *\r
- * License : The MIT License\r
- * Copyright(c) 2009 olyutorskii\r
- */\r
-\r
-package jp.sourceforge.jindolf.parser;\r
-\r
-import java.util.regex.Pattern;\r
-import jp.sourceforge.jindolf.corelib.TalkType;\r
-\r
-/**\r
- * 人狼BBSシステムが出力する各発言箇所のパーサ。\r
- * パース進行に従い{@link TalkHandler}の各種メソッドが呼び出される。\r
- */\r
-public class TalkParser extends AbstractParser{\r
-\r
- private TalkHandler talkHandler;\r
-\r
- private final SeqRange rangepool_1 = new SeqRange();\r
-\r
- /**\r
- * コンストラクタ。\r
- * @param parent 親パーサ\r
- */\r
- public TalkParser(ChainedParser parent){\r
- super(parent);\r
- return;\r
- }\r
-\r
- /**\r
- * {@link TalkHandler}ハンドラを登録する。\r
- * @param talkHandler ハンドラ\r
- */\r
- public void setTalkHandler(TalkHandler talkHandler){\r
- this.talkHandler = talkHandler;\r
- return;\r
- }\r
-\r
- /**\r
- * 各Avatarの個別の発言をパースする。\r
- * 最初のAタグは既にパース済みとする。\r
- * @param talkNo 白発言番号\r
- * @param nameRange Aタグのname属性値の範囲\r
- * @throws HtmlParseException パースエラー\r
- */\r
- public void parseTalk(int talkNo, SeqRange nameRange)\r
- throws HtmlParseException{\r
- this.talkHandler.startTalk();\r
-\r
- this.talkHandler.talkNo(talkNo);\r
- this.talkHandler.talkId(getContent(), nameRange);\r
-\r
- parseName();\r
- parseTime();\r
- parseIcon();\r
- parseType();\r
- parseText();\r
- parseTail();\r
-\r
- this.talkHandler.endTalk();\r
-\r
- return;\r
- }\r
-\r
- private static final Pattern AVATARNAME_PATTERN =\r
- compile("([^<]*)");\r
-\r
- /**\r
- * 発言者名をパースする。\r
- * @throws HtmlParseException パースエラー\r
- */\r
- private void parseName() throws HtmlParseException{\r
- setContextErrorMessage("lost dialog avatar-name");\r
-\r
- SeqRange avatarRange = this.rangepool_1;\r
-\r
- lookingAtAffirm(AVATARNAME_PATTERN);\r
- avatarRange.setLastMatchedGroupRange(getMatcher(), 1);\r
- shrinkRegion();\r
-\r
- this.talkHandler.talkAvatar(getContent(), avatarRange);\r
-\r
- return;\r
- }\r
-\r
- private static final Pattern TALKTIME_PATTERN =\r
- compile(\r
- "</a>"\r
- +SP_I\r
- +"<span class=\"time\">"\r
- +"(?:(午前\u0020)|(午後\u0020))?"\r
- +"([0-9][0-9]?)(?:時\u0020|\\:)"\r
- +"([0-9][0-9]?)分?\u0020"\r
- +"</span>"\r
- +SP_I\r
- +"<table\u0020[^>]*>"\r
- +SP_I\r
- +"(?:<tbody>)?"\r
- +SP_I\r
- +"<tr>"\r
- );\r
-\r
- /**\r
- * 発言時刻をパースする。\r
- * @throws HtmlParseException パースエラー\r
- */\r
- private void parseTime() throws HtmlParseException{\r
- setContextErrorMessage("lost dialog time");\r
-\r
- lookingAtAffirm(TALKTIME_PATTERN);\r
- int hour = parseGroupedInt(3);\r
- int minute = parseGroupedInt(4);\r
- if(isGroupMatched(2)){ // 午後指定\r
- hour = (hour + 12) % 24;\r
- }\r
- shrinkRegion();\r
- sweepSpace();\r
-\r
- this.talkHandler.talkTime(hour, minute);\r
-\r
- return;\r
- }\r
-\r
- private static final Pattern IMGSRC_PATTERN =\r
- compile(\r
- "<td\u0020[^>]*><img\u0020src=\"([^\"]*)\"></td>"\r
- +SP_I\r
- +"<td\u0020[^>]*><img\u0020[^>]*></td>"\r
- );\r
-\r
- /**\r
- * アイコンのURLをパースする。\r
- * @throws HtmlParseException パースエラー\r
- */\r
- private void parseIcon() throws HtmlParseException{\r
- setContextErrorMessage("lost icon url");\r
-\r
- SeqRange urlRange = this.rangepool_1;\r
-\r
- lookingAtAffirm(IMGSRC_PATTERN);\r
- urlRange.setLastMatchedGroupRange(getMatcher(), 1);\r
- shrinkRegion();\r
- sweepSpace();\r
-\r
- this.talkHandler.talkIconUrl(getContent(), urlRange);\r
-\r
- return;\r
- }\r
-\r
- private static final Pattern TALKDIC_PATTERN =\r
- compile(\r
- "<td>" +SP_I+ "<div(?:\u0020[^>]*)?>"\r
- +SP_I\r
- +"<div class=\"mes_"\r
- +"(?:(say)|(think)|(whisper)|(groan))"\r
- +"_body1\">"\r
- );\r
-\r
- /**\r
- * 発言種別をパースする。\r
- * @throws HtmlParseException パースエラー\r
- */\r
- private void parseType() throws HtmlParseException{\r
- setContextErrorMessage("lost dialog type");\r
-\r
- lookingAtAffirm(TALKDIC_PATTERN);\r
- TalkType type;\r
- if(isGroupMatched(1)){\r
- type = TalkType.PUBLIC;\r
- }else if(isGroupMatched(2)){\r
- type = TalkType.PRIVATE;\r
- }else if(isGroupMatched(3)){\r
- type = TalkType.WOLFONLY;\r
- }else if(isGroupMatched(4)){\r
- type = TalkType.GRAVE;\r
- }else{\r
- assert false;\r
- throw buildParseException();\r
- }\r
- shrinkRegion();\r
-\r
- this.talkHandler.talkType(type);\r
-\r
- return;\r
- }\r
-\r
- private static final Pattern TEXT_PATTERN =\r
- compile("([^<>]+)|(<br />)|(<a href=\"[^\"]*\">)|(</a>)");\r
-\r
- /**\r
- * 発言テキストをパースする。\r
- * 前後のホワイトスペースは無視しない。\r
- * @throws HtmlParseException パースエラー\r
- */\r
- private void parseText() throws HtmlParseException{\r
- setContextErrorMessage("lost dialog text");\r
-\r
- SeqRange textRange = this.rangepool_1;\r
-\r
- while(lookingAtProbe(TEXT_PATTERN)){\r
- if(isGroupMatched(1)){\r
- textRange.setLastMatchedGroupRange(getMatcher(), 1);\r
- this.talkHandler.talkText(getContent(), textRange);\r
- }else if(isGroupMatched(2)){ // <br />\r
- this.talkHandler.talkBreak();\r
- }else if(isGroupMatched(3)){ // <a>\r
- // IGNORE\r
- assert true;\r
- }else if(isGroupMatched(4)){ // </a>\r
- // IGNORE\r
- assert true;\r
- }else{\r
- assert false;\r
- throw buildParseException();\r
- }\r
- shrinkRegion();\r
- }\r
-\r
- return;\r
- }\r
-\r
- private static final Pattern TAIL_PATTERN =\r
- compile(\r
- "</div>" // F1603 2d21:12 ペーター発言には注意\r
- +SP_I+ "</div>"\r
- +SP_I+ "</td>"\r
- +SP_I+ "</tr>"\r
- +SP_I+ "(?:</tbody>)?"\r
- +SP_I+ "</table>"\r
- );\r
-\r
- /**\r
- * 発言末尾をパースする。\r
- * @throws HtmlParseException パースエラー\r
- */\r
- private void parseTail() throws HtmlParseException{\r
- setContextErrorMessage("lost dialog termination");\r
-\r
- lookingAtAffirm(TAIL_PATTERN);\r
- shrinkRegion();\r
- sweepSpace();\r
-\r
- return;\r
- }\r
-\r
-}\r
+/*
+ * talk-part parser
+ *
+ * License : The MIT License
+ * Copyright(c) 2009 olyutorskii
+ */
+
+package jp.sourceforge.jindolf.parser;
+
+import java.util.regex.Pattern;
+import jp.sourceforge.jindolf.corelib.TalkType;
+
+/**
+ * 人狼BBSシステムが出力する各発言箇所のパーサ。
+ * パース進行に従い{@link TalkHandler}の各種メソッドが呼び出される。
+ */
+public class TalkParser extends AbstractParser{
+
+ private TalkHandler talkHandler;
+
+ private final SeqRange rangepool_1 = new SeqRange();
+
+ /**
+ * コンストラクタ。
+ * @param parent 親パーサ
+ */
+ public TalkParser(ChainedParser parent){
+ super(parent);
+ return;
+ }
+
+ /**
+ * {@link TalkHandler}ハンドラを登録する。
+ * @param talkHandler ハンドラ
+ */
+ public void setTalkHandler(TalkHandler talkHandler){
+ this.talkHandler = talkHandler;
+ return;
+ }
+
+ /**
+ * 各Avatarの個別の発言をパースする。
+ * 最初のAタグは既にパース済みとする。
+ * @param talkNo 白発言番号
+ * @param nameRange Aタグのname属性値の範囲
+ * @throws HtmlParseException パースエラー
+ */
+ public void parseTalk(int talkNo, SeqRange nameRange)
+ throws HtmlParseException{
+ this.talkHandler.startTalk();
+
+ this.talkHandler.talkNo(talkNo);
+ this.talkHandler.talkId(getContent(), nameRange);
+
+ parseName();
+ parseTime();
+ parseIcon();
+ parseType();
+ parseText();
+ parseTail();
+
+ this.talkHandler.endTalk();
+
+ return;
+ }
+
+ private static final Pattern AVATARNAME_PATTERN =
+ compile("([^<]*)");
+
+ /**
+ * 発言者名をパースする。
+ * @throws HtmlParseException パースエラー
+ */
+ private void parseName() throws HtmlParseException{
+ setContextErrorMessage("lost dialog avatar-name");
+
+ SeqRange avatarRange = this.rangepool_1;
+
+ lookingAtAffirm(AVATARNAME_PATTERN);
+ avatarRange.setLastMatchedGroupRange(getMatcher(), 1);
+ shrinkRegion();
+
+ this.talkHandler.talkAvatar(getContent(), avatarRange);
+
+ return;
+ }
+
+ private static final Pattern TALKTIME_PATTERN =
+ compile(
+ "</a>"
+ +SP_I
+ +"<span class=\"time\">"
+ +"(?:(午前\u0020)|(午後\u0020))?"
+ +"([0-9][0-9]?)(?:時\u0020|\\:)"
+ +"([0-9][0-9]?)分?\u0020"
+ +"</span>"
+ +SP_I
+ +"<table\u0020[^>]*>"
+ +SP_I
+ +"(?:<tbody>)?"
+ +SP_I
+ +"<tr>"
+ );
+
+ /**
+ * 発言時刻をパースする。
+ * @throws HtmlParseException パースエラー
+ */
+ private void parseTime() throws HtmlParseException{
+ setContextErrorMessage("lost dialog time");
+
+ lookingAtAffirm(TALKTIME_PATTERN);
+ int hour = parseGroupedInt(3);
+ int minute = parseGroupedInt(4);
+ if(isGroupMatched(2)){ // 午後指定
+ hour = (hour + 12) % 24;
+ }
+ shrinkRegion();
+ sweepSpace();
+
+ this.talkHandler.talkTime(hour, minute);
+
+ return;
+ }
+
+ private static final Pattern IMGSRC_PATTERN =
+ compile(
+ "<td\u0020[^>]*><img\u0020src=\"([^\"]*)\"></td>"
+ +SP_I
+ +"<td\u0020[^>]*><img\u0020[^>]*></td>"
+ );
+
+ /**
+ * アイコンのURLをパースする。
+ * @throws HtmlParseException パースエラー
+ */
+ private void parseIcon() throws HtmlParseException{
+ setContextErrorMessage("lost icon url");
+
+ SeqRange urlRange = this.rangepool_1;
+
+ lookingAtAffirm(IMGSRC_PATTERN);
+ urlRange.setLastMatchedGroupRange(getMatcher(), 1);
+ shrinkRegion();
+ sweepSpace();
+
+ this.talkHandler.talkIconUrl(getContent(), urlRange);
+
+ return;
+ }
+
+ private static final Pattern TALKDIC_PATTERN =
+ compile(
+ "<td>" +SP_I+ "<div(?:\u0020[^>]*)?>"
+ +SP_I
+ +"<div class=\"mes_"
+ +"(?:(say)|(think)|(whisper)|(groan))"
+ +"_body1\">"
+ );
+
+ /**
+ * 発言種別をパースする。
+ * @throws HtmlParseException パースエラー
+ */
+ private void parseType() throws HtmlParseException{
+ setContextErrorMessage("lost dialog type");
+
+ lookingAtAffirm(TALKDIC_PATTERN);
+ TalkType type;
+ if(isGroupMatched(1)){
+ type = TalkType.PUBLIC;
+ }else if(isGroupMatched(2)){
+ type = TalkType.PRIVATE;
+ }else if(isGroupMatched(3)){
+ type = TalkType.WOLFONLY;
+ }else if(isGroupMatched(4)){
+ type = TalkType.GRAVE;
+ }else{
+ assert false;
+ throw buildParseException();
+ }
+ shrinkRegion();
+
+ this.talkHandler.talkType(type);
+
+ return;
+ }
+
+ private static final Pattern TEXT_PATTERN =
+ compile("([^<>]+)|(<br />)|(<a href=\"[^\"]*\">)|(</a>)");
+
+ /**
+ * 発言テキストをパースする。
+ * 前後のホワイトスペースは無視しない。
+ * @throws HtmlParseException パースエラー
+ */
+ private void parseText() throws HtmlParseException{
+ setContextErrorMessage("lost dialog text");
+
+ SeqRange textRange = this.rangepool_1;
+
+ while(lookingAtProbe(TEXT_PATTERN)){
+ if(isGroupMatched(1)){
+ textRange.setLastMatchedGroupRange(getMatcher(), 1);
+ this.talkHandler.talkText(getContent(), textRange);
+ }else if(isGroupMatched(2)){ // <br />
+ this.talkHandler.talkBreak();
+ }else if(isGroupMatched(3)){ // <a>
+ // IGNORE
+ assert true;
+ }else if(isGroupMatched(4)){ // </a>
+ // IGNORE
+ assert true;
+ }else{
+ assert false;
+ throw buildParseException();
+ }
+ shrinkRegion();
+ }
+
+ return;
+ }
+
+ private static final Pattern TAIL_PATTERN =
+ compile(
+ "</div>" // F1603 2d21:12 ペーター発言には注意
+ +SP_I+ "</div>"
+ +SP_I+ "</td>"
+ +SP_I+ "</tr>"
+ +SP_I+ "(?:</tbody>)?"
+ +SP_I+ "</table>"
+ );
+
+ /**
+ * 発言末尾をパースする。
+ * @throws HtmlParseException パースエラー
+ */
+ private void parseTail() throws HtmlParseException{
+ setContextErrorMessage("lost dialog termination");
+
+ lookingAtAffirm(TAIL_PATTERN);
+ shrinkRegion();
+ sweepSpace();
+
+ return;
+ }
+
+}
-/*\r
- * JinParser パッケージコメント\r
- *\r
- * このファイルは、SunJDK5.0以降に含まれるJavadoc用に用意された、\r
- * 特別な名前を持つソースファイルです。\r
- * このファイルはソースコードを含まず、\r
- * パッケージコメントとパッケージ宣言のみが含まれます。\r
- *\r
- * License : The MIT License\r
- * Copyright(c) 2009 olyutorskii\r
- */\r
-\r
-/**\r
- * これは Jindolf プロジェクトにおける、\r
- * XHTML文書のパース部分を構成するパッケージです。\r
- *\r
- * JinParserライブラリは、CGIゲーム「人狼BBS」のクライアント制作者向けに\r
- * 作られたJavaライブラリです。\r
- * JinParserライブラリは、人狼BBSの専用クライアント開発プロジェクト\r
- * 「Jindolf」から派生しました。\r
- *\r
- * <hr>\r
- *\r
- * 任意のバイトストリームから、\r
- * デコードエラー情報付き文字列{@code DecodedContent}を得るには、\r
- * 次のようにします。\r
- * <pre>\r
- * {@code\r
- * InputStream is = .....\r
- * StreamDecoder decoder = new SjisDecoder();\r
- * ContentBuilder builder = new ContentBuilder();\r
- * decoder.setDecodeHandler(builder);\r
- * try{\r
- * decoder.decode(is);\r
- * }catch(IOException e){\r
- * // ERROR!\r
- * }catch(DecodeException e){\r
- * // ERROR!\r
- * }\r
- * DecodedContent content = builder.getContent();\r
- * }\r
- * </pre>\r
- *\r
- * このようにして得られた文字列をパースして、\r
- * あなたの実装したハンドラ{@code YourHandler}に通知するには、\r
- * 以下のようにします。\r
- * <pre>\r
- * {@code\r
- * HtmlParser parser = new HtmlParser();\r
- * HtmlHandler handler = new YourHandler();\r
- * parser.setBasicHandler(handler);\r
- * parser.setTalkHandler(handler);\r
- * parser.setSysEventHandler(handler);\r
- * try{\r
- * parser.parseAutomatic(content);\r
- * }catch(HtmlParseException e){\r
- * // ERROR!\r
- * }\r
- * }\r
- * </pre>\r
- *\r
- * ハンドラ内部で、パース元となった文字列の一部を切り出したい場合は、\r
- * {@code EntityConverter}を使うのが便利です。\r
- *\r
- * <hr>\r
- *\r
- * <p>\r
- * The MIT License\r
- * </p>\r
- * <p>\r
- * Copyright(c) 2009 olyutorskii\r
- * </p>\r
- * <p>\r
- * Permission is hereby granted, free of charge, to any person obtaining a\r
- * copy of this software and associated documentation files (the "Software"),\r
- * to deal in the Software without restriction, including without limitation\r
- * the rights to use, copy, modify, merge, publish, distribute, sublicense,\r
- * and/or sell copies of the Software, and to permit persons to whom the\r
- * Software is furnished to do so, subject to the following conditions:\r
- * </p>\r
- * <p>\r
- * The above copyright notice and this permission notice shall be included in\r
- * all copies or substantial portions of the Software.\r
- * </p>\r
- * <p>\r
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\r
- * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\r
- * OTHER DEALINGS IN THE SOFTWARE.\r
- * </p>\r
- *\r
- * <hr>\r
- *\r
- * @see <a href="http://jindolf.sourceforge.jp/">\r
- * Jindolfポータルサイト</a>\r
- * @see <a href="http://sourceforge.jp/projects/jindolf/">\r
- * Jindolf開発プロジェクト</a>\r
- */\r
-\r
-package jp.sourceforge.jindolf.parser;\r
-\r
-/* EOF */\r
+/*
+ * JinParser パッケージコメント
+ *
+ * このファイルは、SunJDK5.0以降に含まれるJavadoc用に用意された、
+ * 特別な名前を持つソースファイルです。
+ * このファイルはソースコードを含まず、
+ * パッケージコメントとパッケージ宣言のみが含まれます。
+ *
+ * License : The MIT License
+ * Copyright(c) 2009 olyutorskii
+ */
+
+/**
+ * これは Jindolf プロジェクトにおける、
+ * XHTML文書のパース部分を構成するパッケージです。
+ *
+ * JinParserライブラリは、CGIゲーム「人狼BBS」のクライアント制作者向けに
+ * 作られたJavaライブラリです。
+ * JinParserライブラリは、人狼BBSの専用クライアント開発プロジェクト
+ * 「Jindolf」から派生しました。
+ *
+ * <hr>
+ *
+ * 任意のバイトストリームから、
+ * デコードエラー情報付き文字列{@code DecodedContent}を得るには、
+ * 次のようにします。
+ * <pre>
+ * {@code
+ * InputStream is = .....
+ * StreamDecoder decoder = new SjisDecoder();
+ * ContentBuilder builder = new ContentBuilder();
+ * decoder.setDecodeHandler(builder);
+ * try{
+ * decoder.decode(is);
+ * }catch(IOException e){
+ * // ERROR!
+ * }catch(DecodeException e){
+ * // ERROR!
+ * }
+ * DecodedContent content = builder.getContent();
+ * }
+ * </pre>
+ *
+ * このようにして得られた文字列をパースして、
+ * あなたの実装したハンドラ{@code YourHandler}に通知するには、
+ * 以下のようにします。
+ * <pre>
+ * {@code
+ * HtmlParser parser = new HtmlParser();
+ * HtmlHandler handler = new YourHandler();
+ * parser.setBasicHandler(handler);
+ * parser.setTalkHandler(handler);
+ * parser.setSysEventHandler(handler);
+ * try{
+ * parser.parseAutomatic(content);
+ * }catch(HtmlParseException e){
+ * // ERROR!
+ * }
+ * }
+ * </pre>
+ *
+ * ハンドラ内部で、パース元となった文字列の一部を切り出したい場合は、
+ * {@code EntityConverter}を使うのが便利です。
+ *
+ * <hr>
+ *
+ * <p>
+ * The MIT License
+ * </p>
+ * <p>
+ * Copyright(c) 2009 olyutorskii
+ * </p>
+ * <p>
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ * </p>
+ * <p>
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ * </p>
+ * <p>
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+ * OTHER DEALINGS IN THE SOFTWARE.
+ * </p>
+ *
+ * <hr>
+ *
+ * @see <a href="http://jindolf.sourceforge.jp/">
+ * Jindolfポータルサイト</a>
+ * @see <a href="http://sourceforge.jp/projects/jindolf/">
+ * Jindolf開発プロジェクト</a>
+ */
+
+package jp.sourceforge.jindolf.parser;
+
+/* EOF */
-/*\r
- * License : The MIT License\r
- * Copyright(c) 2009 olyutorskii\r
- */\r
-\r
-package jp.sourceforge.jindolf.parser;\r
-\r
-import java.io.ByteArrayInputStream;\r
-import java.io.IOException;\r
-import java.io.InputStream;\r
-import java.util.ArrayList;\r
-import java.util.List;\r
-import org.junit.After;\r
-import org.junit.AfterClass;\r
-import org.junit.Before;\r
-import org.junit.BeforeClass;\r
-import org.junit.Test;\r
-import static org.junit.Assert.*;\r
-\r
-/**\r
- */\r
-public class ContentBuilderSJTest {\r
-\r
- public ContentBuilderSJTest() {\r
- }\r
-\r
- @BeforeClass\r
- public static void setUpClass() throws Exception{\r
- }\r
-\r
- @AfterClass\r
- public static void tearDownClass() throws Exception{\r
- }\r
-\r
- @Before\r
- public void setUp() {\r
- }\r
-\r
- @After\r
- public void tearDown() {\r
- }\r
-\r
- public static byte[] byteArray(CharSequence seq){\r
- byte[] result;\r
-\r
- List<Byte> byteList = new ArrayList<Byte>();\r
-\r
- int length = seq.length();\r
- for(int pos = 0; pos < length; pos++){\r
- int val = 0;\r
-\r
- char ch = seq.charAt(pos);\r
-\r
- if('0' <= ch && ch <= '9'){\r
- val += ch - '0';\r
- }else if('a' <= ch && ch <= 'f'){\r
- val += ch - 'a' + 10;\r
- }else if('A' <= ch && ch <= 'F'){\r
- val += ch - 'A' + 10;\r
- }else{\r
- continue;\r
- }\r
-\r
- pos++;\r
- if(pos >= length) break;\r
-\r
- val *= 16;\r
- ch = seq.charAt(pos);\r
-\r
- if('0' <= ch && ch <= '9'){\r
- val += ch - '0';\r
- }else if('a' <= ch && ch <= 'f'){\r
- val += ch - 'a' + 10;\r
- }else if('A' <= ch && ch <= 'F'){\r
- val += ch - 'A' + 10;\r
- }else{\r
- continue;\r
- }\r
-\r
- byteList.add((byte)val);\r
- }\r
-\r
- result = new byte[byteList.size()];\r
-\r
- for(int pos = 0; pos < result.length; pos++){\r
- result[pos] = byteList.get(pos);\r
- }\r
-\r
- return result;\r
- }\r
-\r
- /**\r
- * Test of SjisDecoder & ContentBuilder.\r
- */\r
- @Test\r
- public void testDecoding() throws IOException, DecodeException{\r
- System.out.println("Decoding");\r
-\r
- SjisDecoder decoder;\r
- ContentBuilderSJ builder;\r
- byte[] bdata;\r
- InputStream istream;\r
- DecodedContent content;\r
-\r
- decoder = new SjisDecoder();\r
- builder = new ContentBuilderSJ();\r
- decoder.setDecodeHandler(builder);\r
-\r
- bdata = byteArray("20:41:42:43:7e");\r
- istream = new ByteArrayInputStream(bdata);\r
- decoder.decode(istream);\r
- content = builder.getContent();\r
- assertEquals(" ABC~", content.toString());\r
- assertFalse(content.hasDecodeError());\r
-\r
- bdata = byteArray("");\r
- istream = new ByteArrayInputStream(bdata);\r
- decoder.decode(istream);\r
- content = builder.getContent();\r
- assertEquals("", content.toString());\r
- assertFalse(content.hasDecodeError());\r
-\r
- bdata = byteArray("00:0A:0D:1F");\r
- istream = new ByteArrayInputStream(bdata);\r
- decoder.decode(istream);\r
- content = builder.getContent();\r
- assertEquals("\u0000\n\r\u001f", content.toString());\r
- assertFalse(content.hasDecodeError());\r
-\r
- bdata = byteArray("A1:B1:B2:B3:DF");\r
- istream = new ByteArrayInputStream(bdata);\r
- decoder.decode(istream);\r
- content = builder.getContent();\r
- assertEquals("。アイウ゚", content.toString());\r
- assertFalse(content.hasDecodeError());\r
-\r
- bdata = byteArray("8140:82A0:82A2:82A4:889F:EAA4");\r
- istream = new ByteArrayInputStream(bdata);\r
- decoder.decode(istream);\r
- content = builder.getContent();\r
- assertEquals("\u3000あいう亜熙", content.toString());\r
- assertFalse(content.hasDecodeError());\r
-\r
- bdata = byteArray("5c");\r
- istream = new ByteArrayInputStream(bdata);\r
- decoder.decode(istream);\r
- content = builder.getContent();\r
- assertEquals("\\", content.toString());\r
- assertNotSame("\u00a5", content.toString());\r
- assertFalse(content.hasDecodeError());\r
-\r
- bdata = byteArray("8d5c");\r
- istream = new ByteArrayInputStream(bdata);\r
- decoder.decode(istream);\r
- content = builder.getContent();\r
- assertEquals("構", content.toString());\r
- assertFalse(content.hasDecodeError());\r
-\r
- return;\r
- }\r
-\r
- private void assertUnmapError(DecodeErrorInfo einfo,\r
- int charPos,\r
- int b1, int b2 ){\r
- assertEquals(charPos, einfo.getCharPosition());\r
- assertTrue(einfo.has2nd());\r
- assertEquals((byte)b1, einfo.getRawByte1st());\r
- assertEquals((byte)b2, einfo.getRawByte2nd());\r
- return;\r
- }\r
-\r
- /**\r
- * Test of unmappable character.\r
- */\r
- @Test\r
- public void testUnmap() throws IOException, DecodeException{\r
- System.out.println("Unmap");\r
-\r
- SjisDecoder decoder;\r
- ContentBuilderSJ builder;\r
- byte[] bdata;\r
- InputStream istream;\r
- DecodedContent content;\r
- DecodeErrorInfo einfo;\r
-\r
- decoder = new SjisDecoder();\r
- builder = new ContentBuilderSJ();\r
- decoder.setDecodeHandler(builder);\r
-\r
- bdata = byteArray("41:8540:42"); // 9区\r
- istream = new ByteArrayInputStream(bdata);\r
- decoder.decode(istream);\r
- content = builder.getContent();\r
- assertEquals("A?B", content.toString());\r
- assertTrue(content.hasDecodeError());\r
- assertEquals(1, content.getDecodeErrorList().size());\r
- einfo = content.getDecodeErrorList().get(0);\r
- assertUnmapError(einfo, 1, 0x85, 0x40);\r
-\r
- bdata = byteArray("41:8740:42"); // 13区\r
- istream = new ByteArrayInputStream(bdata);\r
- decoder.decode(istream);\r
- content = builder.getContent();\r
- assertEquals("A?B", content.toString());\r
- assertTrue(content.hasDecodeError());\r
- assertEquals(1, content.getDecodeErrorList().size());\r
- einfo = content.getDecodeErrorList().get(0);\r
- assertUnmapError(einfo, 1, 0x87, 0x40);\r
-\r
- bdata = byteArray("41:8840:42"); // 15区\r
- istream = new ByteArrayInputStream(bdata);\r
- decoder.decode(istream);\r
- content = builder.getContent();\r
- assertEquals("A?B", content.toString());\r
- assertTrue(content.hasDecodeError());\r
- assertEquals(1, content.getDecodeErrorList().size());\r
- einfo = content.getDecodeErrorList().get(0);\r
- assertUnmapError(einfo, 1, 0x88, 0x40);\r
-\r
- bdata = byteArray("41:EB40:42"); // 85区\r
- istream = new ByteArrayInputStream(bdata);\r
- decoder.decode(istream);\r
- content = builder.getContent();\r
- assertEquals("A?B", content.toString());\r
- assertTrue(content.hasDecodeError());\r
- assertEquals(1, content.getDecodeErrorList().size());\r
- einfo = content.getDecodeErrorList().get(0);\r
- assertUnmapError(einfo, 1, 0xEB, 0x40);\r
-\r
- bdata = byteArray("41:ED40:42"); // 89区\r
- istream = new ByteArrayInputStream(bdata);\r
- decoder.decode(istream);\r
- content = builder.getContent();\r
- assertEquals("A?B", content.toString());\r
- assertTrue(content.hasDecodeError());\r
- assertEquals(1, content.getDecodeErrorList().size());\r
- einfo = content.getDecodeErrorList().get(0);\r
- assertUnmapError(einfo, 1, 0xED, 0x40);\r
-\r
- bdata = byteArray("41:EEFC:42"); // 92区\r
- istream = new ByteArrayInputStream(bdata);\r
- decoder.decode(istream);\r
- content = builder.getContent();\r
- assertEquals("A?B", content.toString());\r
- assertTrue(content.hasDecodeError());\r
- assertEquals(1, content.getDecodeErrorList().size());\r
- einfo = content.getDecodeErrorList().get(0);\r
- assertUnmapError(einfo, 1, 0xEE, 0xFC);\r
-\r
- bdata = byteArray("41:EF9F:42"); // 94区\r
- istream = new ByteArrayInputStream(bdata);\r
- decoder.decode(istream);\r
- content = builder.getContent();\r
- assertEquals("A?B", content.toString());\r
- assertTrue(content.hasDecodeError());\r
- assertEquals(1, content.getDecodeErrorList().size());\r
- einfo = content.getDecodeErrorList().get(0);\r
- assertUnmapError(einfo, 1, 0xEF, 0x9F);\r
-\r
- return;\r
- }\r
-\r
- private void assertMalformError(DecodeErrorInfo einfo,\r
- int charPos,\r
- int b1 ){\r
- assertEquals(charPos, einfo.getCharPosition());\r
- assertFalse(einfo.has2nd());\r
- assertEquals((byte)b1, einfo.getRawByte1st());\r
- return;\r
- }\r
-\r
- /**\r
- * Test of malformed character.\r
- */\r
- @Test\r
- public void testMalform() throws IOException, DecodeException{\r
- System.out.println("Malform");\r
-\r
- SjisDecoder decoder;\r
- ContentBuilderSJ builder;\r
- byte[] bdata;\r
- InputStream istream;\r
- DecodedContent content;\r
- DecodeErrorInfo einfo;\r
-\r
- decoder = new SjisDecoder();\r
- builder = new ContentBuilderSJ();\r
- decoder.setDecodeHandler(builder);\r
-\r
- bdata = byteArray("31:FD:FE:FF:32");\r
- istream = new ByteArrayInputStream(bdata);\r
- decoder.decode(istream);\r
- content = builder.getContent();\r
- assertEquals("1???2", content.toString());\r
- assertTrue(content.hasDecodeError());\r
- assertEquals(3, content.getDecodeErrorList().size());\r
- einfo = content.getDecodeErrorList().get(0);\r
- assertMalformError(einfo, 1, 0xfd);\r
- einfo = content.getDecodeErrorList().get(1);\r
- assertMalformError(einfo, 2, 0xfe);\r
- einfo = content.getDecodeErrorList().get(2);\r
- assertMalformError(einfo, 3, 0xff);\r
-\r
- bdata = byteArray("31:82:32:33");\r
- istream = new ByteArrayInputStream(bdata);\r
- decoder.decode(istream);\r
- content = builder.getContent();\r
- assertEquals("1?23", content.toString());\r
- assertTrue(content.hasDecodeError());\r
- assertEquals(1, content.getDecodeErrorList().size());\r
- einfo = content.getDecodeErrorList().get(0);\r
- assertMalformError(einfo, 1, 0x82);\r
-\r
- bdata = byteArray("31:32:33:82");\r
- istream = new ByteArrayInputStream(bdata);\r
- decoder.decode(istream);\r
- content = builder.getContent();\r
- assertEquals("123?", content.toString());\r
- assertTrue(content.hasDecodeError());\r
- assertEquals(1, content.getDecodeErrorList().size());\r
- einfo = content.getDecodeErrorList().get(0);\r
- assertMalformError(einfo, 3, 0x82);\r
-\r
- return;\r
- }\r
-\r
- /**\r
- * Test of Bounds buffering.\r
- */\r
- @Test\r
- public void testBounds() throws IOException, DecodeException{\r
- System.out.println("Bounds");\r
-\r
- SjisDecoder decoder;\r
- ContentBuilderSJ builder;\r
- byte[] bdata;\r
- InputStream istream;\r
- DecodedContent content;\r
- DecodeErrorInfo einfo;\r
-\r
- decoder = new SjisDecoder(5, 5);\r
- builder = new ContentBuilderSJ();\r
- decoder.setDecodeHandler(builder);\r
-\r
- bdata = byteArray("31:32:33:34:88" + "9F:35");\r
- istream = new ByteArrayInputStream(bdata);\r
- decoder.decode(istream);\r
- content = builder.getContent();\r
- assertEquals("1234亜5", content.toString());\r
- assertFalse(content.hasDecodeError());\r
- assertEquals(0, content.getDecodeErrorList().size());\r
-\r
- bdata = byteArray("31:32:33:34:82" + "35:36");\r
- istream = new ByteArrayInputStream(bdata);\r
- decoder.decode(istream);\r
- content = builder.getContent();\r
- assertEquals("1234?56", content.toString());\r
- assertTrue(content.hasDecodeError());\r
- assertEquals(1, content.getDecodeErrorList().size());\r
- einfo = content.getDecodeErrorList().get(0);\r
- assertMalformError(einfo, 4, 0x82);\r
-\r
- bdata = byteArray("31:32:33:34:87" + "40:35");\r
- istream = new ByteArrayInputStream(bdata);\r
- decoder.decode(istream);\r
- content = builder.getContent();\r
- assertEquals("1234?5", content.toString());\r
- assertTrue(content.hasDecodeError());\r
- assertEquals(1, content.getDecodeErrorList().size());\r
- einfo = content.getDecodeErrorList().get(0);\r
- assertUnmapError(einfo, 4, 0x87, 0x40);\r
-\r
- decoder = new SjisDecoder(5, 3);\r
- builder = new ContentBuilderSJ();\r
- decoder.setDecodeHandler(builder);\r
-\r
- bdata = byteArray("31:32:33:34:35:36");\r
- istream = new ByteArrayInputStream(bdata);\r
- decoder.decode(istream);\r
- content = builder.getContent();\r
- assertEquals("123456", content.toString());\r
- assertFalse(content.hasDecodeError());\r
- assertEquals(0, content.getDecodeErrorList().size());\r
-\r
- return;\r
- }\r
-\r
-}\r
+/*
+ * License : The MIT License
+ * Copyright(c) 2009 olyutorskii
+ */
+
+package jp.sourceforge.jindolf.parser;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.List;
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import static org.junit.Assert.*;
+
+/**
+ */
+public class ContentBuilderSJTest {
+
+ public ContentBuilderSJTest() {
+ }
+
+ @BeforeClass
+ public static void setUpClass() throws Exception{
+ }
+
+ @AfterClass
+ public static void tearDownClass() throws Exception{
+ }
+
+ @Before
+ public void setUp() {
+ }
+
+ @After
+ public void tearDown() {
+ }
+
+ public static byte[] byteArray(CharSequence seq){
+ byte[] result;
+
+ List<Byte> byteList = new ArrayList<Byte>();
+
+ int length = seq.length();
+ for(int pos = 0; pos < length; pos++){
+ int val = 0;
+
+ char ch = seq.charAt(pos);
+
+ if('0' <= ch && ch <= '9'){
+ val += ch - '0';
+ }else if('a' <= ch && ch <= 'f'){
+ val += ch - 'a' + 10;
+ }else if('A' <= ch && ch <= 'F'){
+ val += ch - 'A' + 10;
+ }else{
+ continue;
+ }
+
+ pos++;
+ if(pos >= length) break;
+
+ val *= 16;
+ ch = seq.charAt(pos);
+
+ if('0' <= ch && ch <= '9'){
+ val += ch - '0';
+ }else if('a' <= ch && ch <= 'f'){
+ val += ch - 'a' + 10;
+ }else if('A' <= ch && ch <= 'F'){
+ val += ch - 'A' + 10;
+ }else{
+ continue;
+ }
+
+ byteList.add((byte)val);
+ }
+
+ result = new byte[byteList.size()];
+
+ for(int pos = 0; pos < result.length; pos++){
+ result[pos] = byteList.get(pos);
+ }
+
+ return result;
+ }
+
+ /**
+ * Test of SjisDecoder & ContentBuilder.
+ */
+ @Test
+ public void testDecoding() throws IOException, DecodeException{
+ System.out.println("Decoding");
+
+ SjisDecoder decoder;
+ ContentBuilderSJ builder;
+ byte[] bdata;
+ InputStream istream;
+ DecodedContent content;
+
+ decoder = new SjisDecoder();
+ builder = new ContentBuilderSJ();
+ decoder.setDecodeHandler(builder);
+
+ bdata = byteArray("20:41:42:43:7e");
+ istream = new ByteArrayInputStream(bdata);
+ decoder.decode(istream);
+ content = builder.getContent();
+ assertEquals(" ABC~", content.toString());
+ assertFalse(content.hasDecodeError());
+
+ bdata = byteArray("");
+ istream = new ByteArrayInputStream(bdata);
+ decoder.decode(istream);
+ content = builder.getContent();
+ assertEquals("", content.toString());
+ assertFalse(content.hasDecodeError());
+
+ bdata = byteArray("00:0A:0D:1F");
+ istream = new ByteArrayInputStream(bdata);
+ decoder.decode(istream);
+ content = builder.getContent();
+ assertEquals("\u0000\n\r\u001f", content.toString());
+ assertFalse(content.hasDecodeError());
+
+ bdata = byteArray("A1:B1:B2:B3:DF");
+ istream = new ByteArrayInputStream(bdata);
+ decoder.decode(istream);
+ content = builder.getContent();
+ assertEquals("。アイウ゚", content.toString());
+ assertFalse(content.hasDecodeError());
+
+ bdata = byteArray("8140:82A0:82A2:82A4:889F:EAA4");
+ istream = new ByteArrayInputStream(bdata);
+ decoder.decode(istream);
+ content = builder.getContent();
+ assertEquals("\u3000あいう亜熙", content.toString());
+ assertFalse(content.hasDecodeError());
+
+ bdata = byteArray("5c");
+ istream = new ByteArrayInputStream(bdata);
+ decoder.decode(istream);
+ content = builder.getContent();
+ assertEquals("\\", content.toString());
+ assertNotSame("\u00a5", content.toString());
+ assertFalse(content.hasDecodeError());
+
+ bdata = byteArray("8d5c");
+ istream = new ByteArrayInputStream(bdata);
+ decoder.decode(istream);
+ content = builder.getContent();
+ assertEquals("構", content.toString());
+ assertFalse(content.hasDecodeError());
+
+ return;
+ }
+
+ private void assertUnmapError(DecodeErrorInfo einfo,
+ int charPos,
+ int b1, int b2 ){
+ assertEquals(charPos, einfo.getCharPosition());
+ assertTrue(einfo.has2nd());
+ assertEquals((byte)b1, einfo.getRawByte1st());
+ assertEquals((byte)b2, einfo.getRawByte2nd());
+ return;
+ }
+
+ /**
+ * Test of unmappable character.
+ */
+ @Test
+ public void testUnmap() throws IOException, DecodeException{
+ System.out.println("Unmap");
+
+ SjisDecoder decoder;
+ ContentBuilderSJ builder;
+ byte[] bdata;
+ InputStream istream;
+ DecodedContent content;
+ DecodeErrorInfo einfo;
+
+ decoder = new SjisDecoder();
+ builder = new ContentBuilderSJ();
+ decoder.setDecodeHandler(builder);
+
+ bdata = byteArray("41:8540:42"); // 9区
+ istream = new ByteArrayInputStream(bdata);
+ decoder.decode(istream);
+ content = builder.getContent();
+ assertEquals("A?B", content.toString());
+ assertTrue(content.hasDecodeError());
+ assertEquals(1, content.getDecodeErrorList().size());
+ einfo = content.getDecodeErrorList().get(0);
+ assertUnmapError(einfo, 1, 0x85, 0x40);
+
+ bdata = byteArray("41:8740:42"); // 13区
+ istream = new ByteArrayInputStream(bdata);
+ decoder.decode(istream);
+ content = builder.getContent();
+ assertEquals("A?B", content.toString());
+ assertTrue(content.hasDecodeError());
+ assertEquals(1, content.getDecodeErrorList().size());
+ einfo = content.getDecodeErrorList().get(0);
+ assertUnmapError(einfo, 1, 0x87, 0x40);
+
+ bdata = byteArray("41:8840:42"); // 15区
+ istream = new ByteArrayInputStream(bdata);
+ decoder.decode(istream);
+ content = builder.getContent();
+ assertEquals("A?B", content.toString());
+ assertTrue(content.hasDecodeError());
+ assertEquals(1, content.getDecodeErrorList().size());
+ einfo = content.getDecodeErrorList().get(0);
+ assertUnmapError(einfo, 1, 0x88, 0x40);
+
+ bdata = byteArray("41:EB40:42"); // 85区
+ istream = new ByteArrayInputStream(bdata);
+ decoder.decode(istream);
+ content = builder.getContent();
+ assertEquals("A?B", content.toString());
+ assertTrue(content.hasDecodeError());
+ assertEquals(1, content.getDecodeErrorList().size());
+ einfo = content.getDecodeErrorList().get(0);
+ assertUnmapError(einfo, 1, 0xEB, 0x40);
+
+ bdata = byteArray("41:ED40:42"); // 89区
+ istream = new ByteArrayInputStream(bdata);
+ decoder.decode(istream);
+ content = builder.getContent();
+ assertEquals("A?B", content.toString());
+ assertTrue(content.hasDecodeError());
+ assertEquals(1, content.getDecodeErrorList().size());
+ einfo = content.getDecodeErrorList().get(0);
+ assertUnmapError(einfo, 1, 0xED, 0x40);
+
+ bdata = byteArray("41:EEFC:42"); // 92区
+ istream = new ByteArrayInputStream(bdata);
+ decoder.decode(istream);
+ content = builder.getContent();
+ assertEquals("A?B", content.toString());
+ assertTrue(content.hasDecodeError());
+ assertEquals(1, content.getDecodeErrorList().size());
+ einfo = content.getDecodeErrorList().get(0);
+ assertUnmapError(einfo, 1, 0xEE, 0xFC);
+
+ bdata = byteArray("41:EF9F:42"); // 94区
+ istream = new ByteArrayInputStream(bdata);
+ decoder.decode(istream);
+ content = builder.getContent();
+ assertEquals("A?B", content.toString());
+ assertTrue(content.hasDecodeError());
+ assertEquals(1, content.getDecodeErrorList().size());
+ einfo = content.getDecodeErrorList().get(0);
+ assertUnmapError(einfo, 1, 0xEF, 0x9F);
+
+ return;
+ }
+
+ private void assertMalformError(DecodeErrorInfo einfo,
+ int charPos,
+ int b1 ){
+ assertEquals(charPos, einfo.getCharPosition());
+ assertFalse(einfo.has2nd());
+ assertEquals((byte)b1, einfo.getRawByte1st());
+ return;
+ }
+
+ /**
+ * Test of malformed character.
+ */
+ @Test
+ public void testMalform() throws IOException, DecodeException{
+ System.out.println("Malform");
+
+ SjisDecoder decoder;
+ ContentBuilderSJ builder;
+ byte[] bdata;
+ InputStream istream;
+ DecodedContent content;
+ DecodeErrorInfo einfo;
+
+ decoder = new SjisDecoder();
+ builder = new ContentBuilderSJ();
+ decoder.setDecodeHandler(builder);
+
+ bdata = byteArray("31:FD:FE:FF:32");
+ istream = new ByteArrayInputStream(bdata);
+ decoder.decode(istream);
+ content = builder.getContent();
+ assertEquals("1???2", content.toString());
+ assertTrue(content.hasDecodeError());
+ assertEquals(3, content.getDecodeErrorList().size());
+ einfo = content.getDecodeErrorList().get(0);
+ assertMalformError(einfo, 1, 0xfd);
+ einfo = content.getDecodeErrorList().get(1);
+ assertMalformError(einfo, 2, 0xfe);
+ einfo = content.getDecodeErrorList().get(2);
+ assertMalformError(einfo, 3, 0xff);
+
+ bdata = byteArray("31:82:32:33");
+ istream = new ByteArrayInputStream(bdata);
+ decoder.decode(istream);
+ content = builder.getContent();
+ assertEquals("1?23", content.toString());
+ assertTrue(content.hasDecodeError());
+ assertEquals(1, content.getDecodeErrorList().size());
+ einfo = content.getDecodeErrorList().get(0);
+ assertMalformError(einfo, 1, 0x82);
+
+ bdata = byteArray("31:32:33:82");
+ istream = new ByteArrayInputStream(bdata);
+ decoder.decode(istream);
+ content = builder.getContent();
+ assertEquals("123?", content.toString());
+ assertTrue(content.hasDecodeError());
+ assertEquals(1, content.getDecodeErrorList().size());
+ einfo = content.getDecodeErrorList().get(0);
+ assertMalformError(einfo, 3, 0x82);
+
+ return;
+ }
+
+ /**
+ * Test of Bounds buffering.
+ */
+ @Test
+ public void testBounds() throws IOException, DecodeException{
+ System.out.println("Bounds");
+
+ SjisDecoder decoder;
+ ContentBuilderSJ builder;
+ byte[] bdata;
+ InputStream istream;
+ DecodedContent content;
+ DecodeErrorInfo einfo;
+
+ decoder = new SjisDecoder(5, 5);
+ builder = new ContentBuilderSJ();
+ decoder.setDecodeHandler(builder);
+
+ bdata = byteArray("31:32:33:34:88" + "9F:35");
+ istream = new ByteArrayInputStream(bdata);
+ decoder.decode(istream);
+ content = builder.getContent();
+ assertEquals("1234亜5", content.toString());
+ assertFalse(content.hasDecodeError());
+ assertEquals(0, content.getDecodeErrorList().size());
+
+ bdata = byteArray("31:32:33:34:82" + "35:36");
+ istream = new ByteArrayInputStream(bdata);
+ decoder.decode(istream);
+ content = builder.getContent();
+ assertEquals("1234?56", content.toString());
+ assertTrue(content.hasDecodeError());
+ assertEquals(1, content.getDecodeErrorList().size());
+ einfo = content.getDecodeErrorList().get(0);
+ assertMalformError(einfo, 4, 0x82);
+
+ bdata = byteArray("31:32:33:34:87" + "40:35");
+ istream = new ByteArrayInputStream(bdata);
+ decoder.decode(istream);
+ content = builder.getContent();
+ assertEquals("1234?5", content.toString());
+ assertTrue(content.hasDecodeError());
+ assertEquals(1, content.getDecodeErrorList().size());
+ einfo = content.getDecodeErrorList().get(0);
+ assertUnmapError(einfo, 4, 0x87, 0x40);
+
+ decoder = new SjisDecoder(5, 3);
+ builder = new ContentBuilderSJ();
+ decoder.setDecodeHandler(builder);
+
+ bdata = byteArray("31:32:33:34:35:36");
+ istream = new ByteArrayInputStream(bdata);
+ decoder.decode(istream);
+ content = builder.getContent();
+ assertEquals("123456", content.toString());
+ assertFalse(content.hasDecodeError());
+ assertEquals(0, content.getDecodeErrorList().size());
+
+ return;
+ }
+
+}
-/*\r
- * License : The MIT License\r
- * Copyright(c) 2010 olyutorskii\r
- */\r
-\r
-package jp.sourceforge.jindolf.parser;\r
-\r
-import org.junit.After;\r
-import org.junit.AfterClass;\r
-import org.junit.Before;\r
-import org.junit.BeforeClass;\r
-import org.junit.Test;\r
-import static org.junit.Assert.*;\r
-\r
-/**\r
- *\r
- */\r
-public class ContentBuilderUCS2Test {\r
-\r
- public ContentBuilderUCS2Test() {\r
- }\r
-\r
- @BeforeClass\r
- public static void setUpClass() throws Exception{\r
- }\r
-\r
- @AfterClass\r
- public static void tearDownClass() throws Exception{\r
- }\r
-\r
- @Before\r
- public void setUp() {\r
- }\r
-\r
- @After\r
- public void tearDown() {\r
- }\r
-\r
- /**\r
- * Test of charToUTF8 method, of class ContentBuilderUCS2.\r
- */\r
- @Test\r
- public void testCharToUTF16(){\r
- System.out.println("charToUTF16");\r
-\r
- char ch;\r
- byte[] result;\r
- \r
- ch = '\ud844';\r
- result = ContentBuilderUCS2.charToUTF16(ch);\r
-\r
- assertEquals(2, result.length);\r
-\r
- return;\r
- }\r
-\r
-}\r
+/*
+ * License : The MIT License
+ * Copyright(c) 2010 olyutorskii
+ */
+
+package jp.sourceforge.jindolf.parser;
+
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import static org.junit.Assert.*;
+
+/**
+ *
+ */
+public class ContentBuilderUCS2Test {
+
+ public ContentBuilderUCS2Test() {
+ }
+
+ @BeforeClass
+ public static void setUpClass() throws Exception{
+ }
+
+ @AfterClass
+ public static void tearDownClass() throws Exception{
+ }
+
+ @Before
+ public void setUp() {
+ }
+
+ @After
+ public void tearDown() {
+ }
+
+ /**
+ * Test of charToUTF8 method, of class ContentBuilderUCS2.
+ */
+ @Test
+ public void testCharToUTF16(){
+ System.out.println("charToUTF16");
+
+ char ch;
+ byte[] result;
+
+ ch = '\ud844';
+ result = ContentBuilderUCS2.charToUTF16(ch);
+
+ assertEquals(2, result.length);
+
+ return;
+ }
+
+}
-/*\r
- * License : The MIT License\r
- * Copyright(c) 2009 olyutorskii\r
- */\r
-\r
-package jp.sourceforge.jindolf.parser;\r
-\r
-import org.junit.After;\r
-import org.junit.AfterClass;\r
-import org.junit.Before;\r
-import org.junit.BeforeClass;\r
-import org.junit.Test;\r
-import static org.junit.Assert.*;\r
-\r
-/**\r
- */\r
-public class DecodeErrorInfoTest {\r
-\r
- public DecodeErrorInfoTest() {\r
- }\r
-\r
- @BeforeClass\r
- public static void setUpClass() throws Exception{\r
- }\r
-\r
- @AfterClass\r
- public static void tearDownClass() throws Exception{\r
- }\r
-\r
- @Before\r
- public void setUp() {\r
- }\r
-\r
- @After\r
- public void tearDown() {\r
- }\r
-\r
- /**\r
- * Test of Constructor\r
- */\r
- @Test\r
- public void testConstructor(){\r
- System.out.println("Constructor");\r
-\r
- new DecodeErrorInfo(99, (byte)0xfe);\r
- new DecodeErrorInfo(999, (byte)0x87, (byte)0x40);\r
-\r
- new DecodeErrorInfo(0, (byte)0xfe);\r
- new DecodeErrorInfo(0, (byte)0x87, (byte)0x40);\r
-\r
- try{\r
- new DecodeErrorInfo(-1, (byte)0xfe);\r
- fail();\r
- }catch(IndexOutOfBoundsException e){\r
- }catch(Throwable e){\r
- fail();\r
- }\r
-\r
- try{\r
- new DecodeErrorInfo(-1, (byte)0x87, (byte)0x40);\r
- fail();\r
- }catch(IndexOutOfBoundsException e){\r
- }catch(Throwable e){\r
- fail();\r
- }\r
-\r
- return;\r
- }\r
-\r
- /**\r
- * Test of getCharPosition method, of class DecodeErrorInfo.\r
- */\r
- @Test\r
- public void testGetCharPosition(){\r
- System.out.println("getCharPosition");\r
-\r
- DecodeErrorInfo info;\r
-\r
- info = new DecodeErrorInfo(99, (byte)0xfe);\r
- assertEquals(99, info.getCharPosition());\r
-\r
- info = new DecodeErrorInfo(999, (byte)0x87, (byte)0x40);\r
- assertEquals(999, info.getCharPosition());\r
-\r
- return;\r
- }\r
-\r
- /**\r
- * Test of has2nd method, of class DecodeErrorInfo.\r
- */\r
- @Test\r
- public void testHas2nd(){\r
- System.out.println("has2nd");\r
-\r
- DecodeErrorInfo info;\r
-\r
- info = new DecodeErrorInfo(99, (byte)0xfe);\r
- assertFalse(info.has2nd());\r
-\r
- info = new DecodeErrorInfo(999, (byte)0x87, (byte)0x40);\r
- assertTrue(info.has2nd());\r
-\r
- return;\r
- }\r
-\r
- /**\r
- * Test of getRawByte1st method, of class DecodeErrorInfo.\r
- */\r
- @Test\r
- public void testGetRawByte1st(){\r
- System.out.println("getRawByte1st");\r
-\r
- DecodeErrorInfo info;\r
-\r
- info = new DecodeErrorInfo(99, (byte)0xfe);\r
- assertEquals((byte)0xfe, info.getRawByte1st());\r
-\r
- info = new DecodeErrorInfo(999, (byte)0x87, (byte)0x40);\r
- assertEquals((byte)0x87, info.getRawByte1st());\r
-\r
- return;\r
- }\r
-\r
- /**\r
- * Test of getRawByte2nd method, of class DecodeErrorInfo.\r
- */\r
- @Test\r
- public void testGetRawByte2nd(){\r
- System.out.println("getRawByte2nd");\r
-\r
- DecodeErrorInfo info;\r
-\r
- info = new DecodeErrorInfo(99, (byte)0xfe);\r
- try{\r
- info.getRawByte2nd();\r
- fail();\r
- }catch(IllegalStateException e){\r
- }catch(Throwable e){\r
- fail();\r
- }\r
-\r
- info = new DecodeErrorInfo(999, (byte)0x87, (byte)0x40);\r
- assertEquals((byte)0x40, info.getRawByte2nd());\r
-\r
- return;\r
- }\r
-\r
- /**\r
- * Test of createGappedClone method, of class DecodeErrorInfo.\r
- */\r
- @Test\r
- public void testCreateGappedClone(){\r
- System.out.println("createGappedClone");\r
-\r
- DecodeErrorInfo info;\r
-\r
- info = new DecodeErrorInfo(99, (byte)0xfe);\r
- info = info.createGappedClone(1);\r
- assertEquals(98, info.getCharPosition());\r
-\r
- info = new DecodeErrorInfo(999, (byte)0x87, (byte)0x40);\r
- info = info.createGappedClone(1);\r
- assertEquals(998, info.getCharPosition());\r
-\r
- info = new DecodeErrorInfo(99, (byte)0xfe);\r
- info = info.createGappedClone(-1);\r
- assertEquals(100, info.getCharPosition());\r
-\r
- info = new DecodeErrorInfo(999, (byte)0x87, (byte)0x40);\r
- info = info.createGappedClone(-1);\r
- assertEquals(1000, info.getCharPosition());\r
-\r
- info = new DecodeErrorInfo(99, (byte)0xfe);\r
- info = info.createGappedClone(99);\r
- assertEquals(0, info.getCharPosition());\r
-\r
- info = new DecodeErrorInfo(999, (byte)0x87, (byte)0x40);\r
- info = info.createGappedClone(999);\r
- assertEquals(0, info.getCharPosition());\r
-\r
- info = new DecodeErrorInfo(99, (byte)0xfe);\r
- try{\r
- info = info.createGappedClone(100);\r
- fail();\r
- }catch(IndexOutOfBoundsException e){\r
- }catch(Throwable e){\r
- fail();\r
- }\r
-\r
- info = new DecodeErrorInfo(999, (byte)0x87, (byte)0x40);\r
- try{\r
- info = info.createGappedClone(1000);\r
- fail();\r
- }catch(IndexOutOfBoundsException e){\r
- }catch(Throwable e){\r
- fail();\r
- }\r
-\r
- return;\r
- }\r
-\r
- /**\r
- * Test of toString method, of class DecodeErrorInfo.\r
- */\r
- @Test\r
- public void testToString(){\r
- System.out.println("toString");\r
-\r
- DecodeErrorInfo info;\r
-\r
- info = new DecodeErrorInfo(99, (byte)0x09);\r
- assertEquals("start:99 09", info.toString());\r
-\r
- info = new DecodeErrorInfo(99, (byte)0xfe);\r
- assertEquals("start:99 fe", info.toString());\r
-\r
- info = new DecodeErrorInfo(999, (byte)0x08, (byte)0x09);\r
- assertEquals("start:999 08:09", info.toString());\r
-\r
- info = new DecodeErrorInfo(999, (byte)0x87, (byte)0x40);\r
- assertEquals("start:999 87:40", info.toString());\r
-\r
- return;\r
- }\r
-\r
- /**\r
- * Test of POS_COMPARATOR.\r
- */\r
- @Test\r
- public void testCompare(){\r
- System.out.println("POS_COMPARATOR");\r
-\r
- DecodeErrorInfo info;\r
- DecodeErrorInfo other;\r
-\r
- info = new DecodeErrorInfo(99, (byte)0xfe);\r
- other = new DecodeErrorInfo(98, (byte)0xfe);\r
- assertTrue(DecodeErrorInfo.POS_COMPARATOR.compare(info, other) > 0);\r
-\r
- info = new DecodeErrorInfo(99, (byte)0xfe);\r
- other = new DecodeErrorInfo(100, (byte)0xfe);\r
- assertTrue(DecodeErrorInfo.POS_COMPARATOR.compare(info, other) < 0);\r
-\r
- info = new DecodeErrorInfo(99, (byte)0xfe);\r
- other = new DecodeErrorInfo(99, (byte)0xfe);\r
- assertTrue(DecodeErrorInfo.POS_COMPARATOR.compare(info, other) == 0);\r
-\r
- assertTrue(DecodeErrorInfo.POS_COMPARATOR.compare(null, other) < 0);\r
- assertTrue(DecodeErrorInfo.POS_COMPARATOR.compare(info, null) > 0);\r
- assertTrue(DecodeErrorInfo.POS_COMPARATOR.compare(null, null) == 0);\r
-\r
- return;\r
- }\r
-\r
-}\r
+/*
+ * License : The MIT License
+ * Copyright(c) 2009 olyutorskii
+ */
+
+package jp.sourceforge.jindolf.parser;
+
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import static org.junit.Assert.*;
+
+/**
+ */
+public class DecodeErrorInfoTest {
+
+ public DecodeErrorInfoTest() {
+ }
+
+ @BeforeClass
+ public static void setUpClass() throws Exception{
+ }
+
+ @AfterClass
+ public static void tearDownClass() throws Exception{
+ }
+
+ @Before
+ public void setUp() {
+ }
+
+ @After
+ public void tearDown() {
+ }
+
+ /**
+ * Test of Constructor
+ */
+ @Test
+ public void testConstructor(){
+ System.out.println("Constructor");
+
+ new DecodeErrorInfo(99, (byte)0xfe);
+ new DecodeErrorInfo(999, (byte)0x87, (byte)0x40);
+
+ new DecodeErrorInfo(0, (byte)0xfe);
+ new DecodeErrorInfo(0, (byte)0x87, (byte)0x40);
+
+ try{
+ new DecodeErrorInfo(-1, (byte)0xfe);
+ fail();
+ }catch(IndexOutOfBoundsException e){
+ }catch(Throwable e){
+ fail();
+ }
+
+ try{
+ new DecodeErrorInfo(-1, (byte)0x87, (byte)0x40);
+ fail();
+ }catch(IndexOutOfBoundsException e){
+ }catch(Throwable e){
+ fail();
+ }
+
+ return;
+ }
+
+ /**
+ * Test of getCharPosition method, of class DecodeErrorInfo.
+ */
+ @Test
+ public void testGetCharPosition(){
+ System.out.println("getCharPosition");
+
+ DecodeErrorInfo info;
+
+ info = new DecodeErrorInfo(99, (byte)0xfe);
+ assertEquals(99, info.getCharPosition());
+
+ info = new DecodeErrorInfo(999, (byte)0x87, (byte)0x40);
+ assertEquals(999, info.getCharPosition());
+
+ return;
+ }
+
+ /**
+ * Test of has2nd method, of class DecodeErrorInfo.
+ */
+ @Test
+ public void testHas2nd(){
+ System.out.println("has2nd");
+
+ DecodeErrorInfo info;
+
+ info = new DecodeErrorInfo(99, (byte)0xfe);
+ assertFalse(info.has2nd());
+
+ info = new DecodeErrorInfo(999, (byte)0x87, (byte)0x40);
+ assertTrue(info.has2nd());
+
+ return;
+ }
+
+ /**
+ * Test of getRawByte1st method, of class DecodeErrorInfo.
+ */
+ @Test
+ public void testGetRawByte1st(){
+ System.out.println("getRawByte1st");
+
+ DecodeErrorInfo info;
+
+ info = new DecodeErrorInfo(99, (byte)0xfe);
+ assertEquals((byte)0xfe, info.getRawByte1st());
+
+ info = new DecodeErrorInfo(999, (byte)0x87, (byte)0x40);
+ assertEquals((byte)0x87, info.getRawByte1st());
+
+ return;
+ }
+
+ /**
+ * Test of getRawByte2nd method, of class DecodeErrorInfo.
+ */
+ @Test
+ public void testGetRawByte2nd(){
+ System.out.println("getRawByte2nd");
+
+ DecodeErrorInfo info;
+
+ info = new DecodeErrorInfo(99, (byte)0xfe);
+ try{
+ info.getRawByte2nd();
+ fail();
+ }catch(IllegalStateException e){
+ }catch(Throwable e){
+ fail();
+ }
+
+ info = new DecodeErrorInfo(999, (byte)0x87, (byte)0x40);
+ assertEquals((byte)0x40, info.getRawByte2nd());
+
+ return;
+ }
+
+ /**
+ * Test of createGappedClone method, of class DecodeErrorInfo.
+ */
+ @Test
+ public void testCreateGappedClone(){
+ System.out.println("createGappedClone");
+
+ DecodeErrorInfo info;
+
+ info = new DecodeErrorInfo(99, (byte)0xfe);
+ info = info.createGappedClone(1);
+ assertEquals(98, info.getCharPosition());
+
+ info = new DecodeErrorInfo(999, (byte)0x87, (byte)0x40);
+ info = info.createGappedClone(1);
+ assertEquals(998, info.getCharPosition());
+
+ info = new DecodeErrorInfo(99, (byte)0xfe);
+ info = info.createGappedClone(-1);
+ assertEquals(100, info.getCharPosition());
+
+ info = new DecodeErrorInfo(999, (byte)0x87, (byte)0x40);
+ info = info.createGappedClone(-1);
+ assertEquals(1000, info.getCharPosition());
+
+ info = new DecodeErrorInfo(99, (byte)0xfe);
+ info = info.createGappedClone(99);
+ assertEquals(0, info.getCharPosition());
+
+ info = new DecodeErrorInfo(999, (byte)0x87, (byte)0x40);
+ info = info.createGappedClone(999);
+ assertEquals(0, info.getCharPosition());
+
+ info = new DecodeErrorInfo(99, (byte)0xfe);
+ try{
+ info = info.createGappedClone(100);
+ fail();
+ }catch(IndexOutOfBoundsException e){
+ }catch(Throwable e){
+ fail();
+ }
+
+ info = new DecodeErrorInfo(999, (byte)0x87, (byte)0x40);
+ try{
+ info = info.createGappedClone(1000);
+ fail();
+ }catch(IndexOutOfBoundsException e){
+ }catch(Throwable e){
+ fail();
+ }
+
+ return;
+ }
+
+ /**
+ * Test of toString method, of class DecodeErrorInfo.
+ */
+ @Test
+ public void testToString(){
+ System.out.println("toString");
+
+ DecodeErrorInfo info;
+
+ info = new DecodeErrorInfo(99, (byte)0x09);
+ assertEquals("start:99 09", info.toString());
+
+ info = new DecodeErrorInfo(99, (byte)0xfe);
+ assertEquals("start:99 fe", info.toString());
+
+ info = new DecodeErrorInfo(999, (byte)0x08, (byte)0x09);
+ assertEquals("start:999 08:09", info.toString());
+
+ info = new DecodeErrorInfo(999, (byte)0x87, (byte)0x40);
+ assertEquals("start:999 87:40", info.toString());
+
+ return;
+ }
+
+ /**
+ * Test of POS_COMPARATOR.
+ */
+ @Test
+ public void testCompare(){
+ System.out.println("POS_COMPARATOR");
+
+ DecodeErrorInfo info;
+ DecodeErrorInfo other;
+
+ info = new DecodeErrorInfo(99, (byte)0xfe);
+ other = new DecodeErrorInfo(98, (byte)0xfe);
+ assertTrue(DecodeErrorInfo.POS_COMPARATOR.compare(info, other) > 0);
+
+ info = new DecodeErrorInfo(99, (byte)0xfe);
+ other = new DecodeErrorInfo(100, (byte)0xfe);
+ assertTrue(DecodeErrorInfo.POS_COMPARATOR.compare(info, other) < 0);
+
+ info = new DecodeErrorInfo(99, (byte)0xfe);
+ other = new DecodeErrorInfo(99, (byte)0xfe);
+ assertTrue(DecodeErrorInfo.POS_COMPARATOR.compare(info, other) == 0);
+
+ assertTrue(DecodeErrorInfo.POS_COMPARATOR.compare(null, other) < 0);
+ assertTrue(DecodeErrorInfo.POS_COMPARATOR.compare(info, null) > 0);
+ assertTrue(DecodeErrorInfo.POS_COMPARATOR.compare(null, null) == 0);
+
+ return;
+ }
+
+}
-/*\r
- * License : The MIT License\r
- * Copyright(c) 2009 olyutorskii\r
- */\r
-\r
-package jp.sourceforge.jindolf.parser;\r
-\r
-import org.junit.After;\r
-import org.junit.AfterClass;\r
-import org.junit.Before;\r
-import org.junit.BeforeClass;\r
-import org.junit.Test;\r
-import static org.junit.Assert.*;\r
-\r
-/**\r
- */\r
-public class DecodeExceptionTest {\r
-\r
- public DecodeExceptionTest() {\r
- }\r
-\r
- @BeforeClass\r
- public static void setUpClass() throws Exception{\r
- }\r
-\r
- @AfterClass\r
- public static void tearDownClass() throws Exception{\r
- }\r
-\r
- @Before\r
- public void setUp() {\r
- }\r
-\r
- @After\r
- public void tearDown() {\r
- }\r
-\r
- /**\r
- * Test of getBytePos method, of class DecodeException.\r
- */\r
- @Test\r
- public void testGetBytePos(){\r
- System.out.println("getBytePos");\r
-\r
- DecodeException ex;\r
-\r
- ex = new DecodeException();\r
- assertTrue(0 > ex.getBytePos());\r
-\r
- ex = new DecodeException("abc");\r
- assertTrue(0 > ex.getBytePos());\r
-\r
- ex = new DecodeException(10, 11);\r
- assertEquals(10, ex.getBytePos());\r
-\r
- ex = new DecodeException("abc", 10, 11);\r
- assertEquals(10, ex.getBytePos());\r
-\r
- return;\r
- }\r
-\r
- /**\r
- * Test of getCharPos method, of class DecodeException.\r
- */\r
- @Test\r
- public void testGetCharPos(){\r
- System.out.println("getCharPos");\r
-\r
- DecodeException ex;\r
-\r
- ex = new DecodeException();\r
- assertTrue(0 > ex.getCharPos());\r
-\r
- ex = new DecodeException("abc");\r
- assertTrue(0 > ex.getCharPos());\r
-\r
- ex = new DecodeException(10, 11);\r
- assertEquals(11, ex.getCharPos());\r
-\r
- ex = new DecodeException("abc", 10, 11);\r
- assertEquals(11, ex.getCharPos());\r
-\r
- return;\r
- }\r
-\r
- /**\r
- * Test of getMessage method, of class DecodeException.\r
- */\r
- @Test\r
- public void testGetMessage(){\r
- System.out.println("getMessage");\r
-\r
- DecodeException ex;\r
-\r
- ex = new DecodeException();\r
- assertEquals("bytePos=-1 charPos=-1", ex.getMessage());\r
-\r
- ex = new DecodeException("abc");\r
- assertEquals("abc bytePos=-1 charPos=-1", ex.getMessage());\r
-\r
- ex = new DecodeException(10, 11);\r
- assertEquals("bytePos=10 charPos=11", ex.getMessage());\r
-\r
- ex = new DecodeException("abc", 10, 11);\r
- assertEquals("abc bytePos=10 charPos=11", ex.getMessage());\r
-\r
- return;\r
- }\r
-\r
-}\r
+/*
+ * License : The MIT License
+ * Copyright(c) 2009 olyutorskii
+ */
+
+package jp.sourceforge.jindolf.parser;
+
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import static org.junit.Assert.*;
+
+/**
+ */
+public class DecodeExceptionTest {
+
+ public DecodeExceptionTest() {
+ }
+
+ @BeforeClass
+ public static void setUpClass() throws Exception{
+ }
+
+ @AfterClass
+ public static void tearDownClass() throws Exception{
+ }
+
+ @Before
+ public void setUp() {
+ }
+
+ @After
+ public void tearDown() {
+ }
+
+ /**
+ * Test of getBytePos method, of class DecodeException.
+ */
+ @Test
+ public void testGetBytePos(){
+ System.out.println("getBytePos");
+
+ DecodeException ex;
+
+ ex = new DecodeException();
+ assertTrue(0 > ex.getBytePos());
+
+ ex = new DecodeException("abc");
+ assertTrue(0 > ex.getBytePos());
+
+ ex = new DecodeException(10, 11);
+ assertEquals(10, ex.getBytePos());
+
+ ex = new DecodeException("abc", 10, 11);
+ assertEquals(10, ex.getBytePos());
+
+ return;
+ }
+
+ /**
+ * Test of getCharPos method, of class DecodeException.
+ */
+ @Test
+ public void testGetCharPos(){
+ System.out.println("getCharPos");
+
+ DecodeException ex;
+
+ ex = new DecodeException();
+ assertTrue(0 > ex.getCharPos());
+
+ ex = new DecodeException("abc");
+ assertTrue(0 > ex.getCharPos());
+
+ ex = new DecodeException(10, 11);
+ assertEquals(11, ex.getCharPos());
+
+ ex = new DecodeException("abc", 10, 11);
+ assertEquals(11, ex.getCharPos());
+
+ return;
+ }
+
+ /**
+ * Test of getMessage method, of class DecodeException.
+ */
+ @Test
+ public void testGetMessage(){
+ System.out.println("getMessage");
+
+ DecodeException ex;
+
+ ex = new DecodeException();
+ assertEquals("bytePos=-1 charPos=-1", ex.getMessage());
+
+ ex = new DecodeException("abc");
+ assertEquals("abc bytePos=-1 charPos=-1", ex.getMessage());
+
+ ex = new DecodeException(10, 11);
+ assertEquals("bytePos=10 charPos=11", ex.getMessage());
+
+ ex = new DecodeException("abc", 10, 11);
+ assertEquals("abc bytePos=10 charPos=11", ex.getMessage());
+
+ return;
+ }
+
+}
-/*\r
- * License : The MIT License\r
- * Copyright(c) 2009 olyutorskii\r
- */\r
-\r
-package jp.sourceforge.jindolf.parser;\r
-\r
-import java.util.ArrayList;\r
-import java.util.List;\r
-import org.junit.After;\r
-import org.junit.AfterClass;\r
-import org.junit.Before;\r
-import org.junit.BeforeClass;\r
-import org.junit.Test;\r
-import static org.junit.Assert.*;\r
-\r
-/**\r
- */\r
-public class DecodedContentTest {\r
-\r
- public DecodedContentTest() {\r
- }\r
-\r
- @BeforeClass\r
- public static void setUpClass() throws Exception{\r
- }\r
-\r
- @AfterClass\r
- public static void tearDownClass() throws Exception{\r
- }\r
-\r
- @Before\r
- public void setUp() {\r
- }\r
-\r
- @After\r
- public void tearDown() {\r
- }\r
-\r
- /**\r
- * Test of Constructor, of class DecodedContent.\r
- */\r
- @Test\r
- public void testConstructor(){\r
- System.out.println("Constructor");\r
-\r
- DecodedContent content;\r
-\r
- content = new DecodedContent();\r
- assertEquals("", content.toString());\r
-\r
- content = new DecodedContent("abc");\r
- assertEquals("abc", content.toString());\r
-\r
- content = new DecodedContent(128);\r
- assertEquals("", content.toString());\r
-\r
- content = new DecodedContent(0);\r
- assertEquals("", content.toString());\r
- content.append("abc");\r
- assertEquals("abc", content.toString());\r
-\r
- try{\r
- content = new DecodedContent(-1);\r
- fail();\r
- }catch(NegativeArraySizeException e){\r
- }catch(Throwable e){\r
- fail();\r
- }\r
-\r
- return;\r
- }\r
-\r
- /**\r
- * Test of init method, of class DecodedContent.\r
- */\r
- @Test\r
- public void testInit(){\r
- System.out.println("init");\r
-\r
- DecodedContent content;\r
-\r
- content = new DecodedContent();\r
- content.append("abc");\r
- content.addDecodeError((byte)0xff);\r
- content.append("def");\r
- assertEquals("abc?def", content.toString());\r
- assertEquals(1, content.getDecodeErrorList().size());\r
-\r
- content.init();\r
- assertEquals("", content.toString());\r
- assertEquals(0, content.getDecodeErrorList().size());\r
-\r
- content.append('X');\r
- assertEquals("X", content.toString());\r
-\r
- return;\r
- }\r
-\r
- /**\r
- * Test of hasDecodeError method, of class DecodedContent.\r
- */\r
- @Test\r
- public void testHasDecodeError(){\r
- System.out.println("hasDecodeError");\r
-\r
- DecodedContent content;\r
-\r
- content = new DecodedContent();\r
- assertFalse(content.hasDecodeError());\r
-\r
- content.append("a");\r
- assertFalse(content.hasDecodeError());\r
-\r
- content.addDecodeError((byte)0xff);\r
- assertTrue(content.hasDecodeError());\r
-\r
- content.append("b");\r
- assertTrue(content.hasDecodeError());\r
-\r
- content.init();\r
- assertFalse(content.hasDecodeError());\r
-\r
- content.append("c");\r
- assertFalse(content.hasDecodeError());\r
-\r
- content = new DecodedContent();\r
- List list = content.getDecodeErrorList();\r
- assertEquals(0, list.size());\r
- assertFalse(content.hasDecodeError());\r
-\r
- return;\r
- }\r
-\r
- /**\r
- * Test of getDecodeErrorList method, of class DecodedContent.\r
- */\r
- @Test\r
- public void testGetDecodeErrorList(){\r
- System.out.println("getDecodeErrorList");\r
-\r
- DecodedContent content;\r
- List<DecodeErrorInfo> list;\r
-\r
- content = new DecodedContent();\r
- list = content.getDecodeErrorList();\r
- assertEquals(0, list.size());\r
-\r
- content.append("abc");\r
- list = content.getDecodeErrorList();\r
- assertEquals(0, list.size());\r
-\r
- content.addDecodeError((byte)0xff);\r
- list = content.getDecodeErrorList();\r
- assertEquals(1, list.size());\r
-\r
- content.append("def");\r
- list = content.getDecodeErrorList();\r
- assertEquals(1, list.size());\r
-\r
- content.addDecodeError((byte)0x03, (byte)0x04);\r
- list = content.getDecodeErrorList();\r
- assertEquals(2, list.size());\r
-\r
- return;\r
- }\r
-\r
- /**\r
- * Test of getRawContent method, of class DecodedContent.\r
- */\r
- @Test\r
- public void testGetRawContent(){\r
- System.out.println("getRawContent");\r
-\r
- DecodedContent content;\r
-\r
- content = new DecodedContent();\r
- assertEquals("", content.getRawContent().toString());\r
-\r
- content.append("a");\r
- assertEquals("a", content.getRawContent().toString());\r
-\r
- content.addDecodeError((byte)0xff);\r
- assertEquals("a?", content.getRawContent().toString());\r
-\r
- content.append("b");\r
- assertEquals("a?b", content.getRawContent().toString());\r
-\r
- assertEquals(content.toString(), content.getRawContent().toString());\r
-\r
- return;\r
- }\r
-\r
- /**\r
- * Test of charAt method, of class DecodedContent.\r
- */\r
- @Test\r
- public void testCharAt(){\r
- System.out.println("charAt");\r
-\r
- DecodedContent content;\r
-\r
- content = new DecodedContent();\r
- content.append("12345");\r
- assertEquals('1', content.charAt(0));\r
- assertEquals('3', content.charAt(2));\r
- assertEquals('5', content.charAt(4));\r
-\r
- try{\r
- content.charAt(-1);\r
- fail();\r
- }catch(IndexOutOfBoundsException e){\r
- }catch(Throwable e){\r
- fail();\r
- }\r
-\r
- try{\r
- content.charAt(5);\r
- fail();\r
- }catch(IndexOutOfBoundsException e){\r
- }catch(Throwable e){\r
- fail();\r
- }\r
-\r
- return;\r
- }\r
-\r
- /**\r
- * Test of length method, of class DecodedContent.\r
- */\r
- @Test\r
- public void testLength(){\r
- System.out.println("length");\r
-\r
- DecodedContent content;\r
-\r
- content = new DecodedContent();\r
- assertEquals(0, content.length());\r
-\r
- content.append("12345");\r
- assertEquals(5, content.length());\r
-\r
- content.addDecodeError((byte)0xff);\r
- assertEquals(6, content.length());\r
-\r
- content.init();\r
- assertEquals(0, content.length());\r
-\r
- return;\r
- }\r
-\r
- /**\r
- * Test of subSequence method, of class DecodedContent.\r
- */\r
- @Test\r
- public void testSubSequence(){\r
- System.out.println("subSequence");\r
-\r
- DecodedContent content;\r
-\r
- content = new DecodedContent();\r
-\r
- content.append("12345");\r
- assertEquals("234", content.subSequence(1, 4).toString());\r
-\r
- try{\r
- content.subSequence(-1, 4);\r
- fail();\r
- }catch(IndexOutOfBoundsException e){\r
- }catch(Throwable e){\r
- fail();\r
- }\r
-\r
- try{\r
- content.subSequence(1, 6);\r
- fail();\r
- }catch(IndexOutOfBoundsException e){\r
- }catch(Throwable e){\r
- fail();\r
- }\r
-\r
- try{\r
- content.subSequence(4, 1);\r
- fail();\r
- }catch(IndexOutOfBoundsException e){\r
- }catch(Throwable e){\r
- fail();\r
- }\r
-\r
- return;\r
- }\r
-\r
- /**\r
- * Test of subContent method, of class DecodedContent.\r
- */\r
- @Test\r
- public void testSubContent(){\r
- System.out.println("subContent");\r
-\r
- DecodedContent content;\r
-\r
- content = new DecodedContent();\r
-\r
- content.append("12345");\r
- assertEquals("234", content.subContent(1, 4).toString());\r
-\r
- try{\r
- content.subContent(-1, 4);\r
- fail();\r
- }catch(IndexOutOfBoundsException e){\r
- }catch(Throwable e){\r
- fail();\r
- }\r
-\r
- try{\r
- content.subContent(1, 6);\r
- fail();\r
- }catch(IndexOutOfBoundsException e){\r
- }catch(Throwable e){\r
- fail();\r
- }\r
-\r
- try{\r
- content.subContent(4, 1);\r
- fail();\r
- }catch(IndexOutOfBoundsException e){\r
- }catch(Throwable e){\r
- fail();\r
- }\r
-\r
- content = new DecodedContent();\r
- content.append("ab");\r
- content.addDecodeError((byte)0x01);\r
- content.append("de");\r
- content = content.subContent(1,4);\r
- assertEquals("b?d", content.toString());\r
-\r
- List<DecodeErrorInfo> list = content.getDecodeErrorList();\r
- assertEquals(1, list.size());\r
- assertEquals((byte)0x01, list.get(0).getRawByte1st());\r
-\r
- return;\r
- }\r
-\r
- /**\r
- * Test of append method, of class DecodedContent.\r
- */\r
- @Test\r
- public void testAppend_char(){\r
- System.out.println("append");\r
-\r
- DecodedContent content;\r
-\r
- content = new DecodedContent();\r
- content.append('a');\r
- assertEquals("a", content.toString());\r
-\r
- return;\r
- }\r
-\r
- /**\r
- * Test of append method, of class DecodedContent.\r
- */\r
- @Test\r
- public void testAppend_CharSequence(){\r
- System.out.println("append");\r
-\r
- DecodedContent content;\r
-\r
- content = new DecodedContent();\r
- CharSequence seq = "abc";\r
- content.append(seq);\r
- assertEquals("abc", content.toString());\r
-\r
- return;\r
- }\r
-\r
- /**\r
- * Test of append method, of class DecodedContent.\r
- */\r
- @Test\r
- public void testAppend_3args_1(){\r
- System.out.println("append");\r
-\r
- DecodedContent content;\r
-\r
- content = new DecodedContent();\r
- content.append("abc");\r
- assertEquals("abc", content.toString());\r
-\r
- CharSequence seq = "12345";\r
- content.append(seq, 1, 4);\r
- assertEquals("abc234", content.toString());\r
-\r
- return;\r
- }\r
-\r
- /**\r
- * Test of append method, of class DecodedContent.\r
- */\r
- @Test\r
- public void testAppend_3args_2(){\r
- System.out.println("append");\r
-\r
- DecodedContent content;\r
-\r
- content = new DecodedContent();\r
- content.append("abc");\r
-\r
- DecodedContent other;\r
- other = new DecodedContent();\r
- other.append("12345");\r
-\r
- content.append(other, 1, 4);\r
- assertEquals("abc234", content.toString());\r
-\r
- content = new DecodedContent();\r
- content.append("abc");\r
-\r
- other = new DecodedContent();\r
- other.addDecodeError((byte)0x01);\r
- other.addDecodeError((byte)0x02);\r
- other.addDecodeError((byte)0x03);\r
- other.addDecodeError((byte)0x04);\r
- other.addDecodeError((byte)0x05);\r
-\r
- content.append(other, 1, 4);\r
- assertEquals("abc???", content.toString());\r
-\r
- List<DecodeErrorInfo> list = content.getDecodeErrorList();\r
- assertEquals(3, list.size());\r
-\r
- DecodeErrorInfo info;\r
-\r
- info = list.get(0);\r
- assertEquals(3, info.getCharPosition());\r
- assertEquals((byte)0x02, info.getRawByte1st());\r
- info = list.get(1);\r
- assertEquals(4, info.getCharPosition());\r
- assertEquals((byte)0x03, info.getRawByte1st());\r
- info = list.get(2);\r
- assertEquals(5, info.getCharPosition());\r
- assertEquals((byte)0x04, info.getRawByte1st());\r
-\r
- return;\r
- }\r
-\r
- /**\r
- * Test of addDecodeError method, of class DecodedContent.\r
- */\r
- @Test\r
- public void testAddDecodeError_byte(){\r
- System.out.println("addDecodeError");\r
-\r
- DecodedContent content;\r
-\r
- content = new DecodedContent();\r
- content.append("abc");\r
- content.addDecodeError((byte)0xfe);\r
- content.append("def");\r
- content.addDecodeError((byte)0xff);\r
-\r
- assertEquals("abc?def?", content.toString());\r
- List<DecodeErrorInfo> list = content.getDecodeErrorList();\r
- assertEquals(2, list.size());\r
-\r
- DecodeErrorInfo info;\r
-\r
- info = list.get(0);\r
- assertEquals(3, list.get(0).getCharPosition());\r
- assertFalse(info.has2nd());\r
- assertEquals((byte)0xfe, info.getRawByte1st());\r
-\r
- info = list.get(1);\r
- assertEquals(7, info.getCharPosition());\r
- assertFalse(info.has2nd());\r
- assertEquals((byte)0xff, info.getRawByte1st());\r
-\r
- return;\r
- }\r
-\r
- /**\r
- * Test of addDecodeError method, of class DecodedContent.\r
- */\r
- @Test\r
- public void testAddDecodeError_byte_byte(){\r
- System.out.println("addDecodeError");\r
-\r
- DecodedContent content;\r
-\r
- content = new DecodedContent();\r
- content.append("abc");\r
- content.addDecodeError((byte)0x01, (byte)0x02);\r
- content.append("def");\r
- content.addDecodeError((byte)0xfe, (byte)0xff);\r
-\r
- assertEquals("abc?def?", content.toString());\r
- List<DecodeErrorInfo> list = content.getDecodeErrorList();\r
- assertEquals(2, list.size());\r
-\r
- DecodeErrorInfo info;\r
-\r
- info = list.get(0);\r
- assertEquals(3, list.get(0).getCharPosition());\r
- assertTrue(info.has2nd());\r
- assertEquals((byte)0x01, info.getRawByte1st());\r
- assertEquals((byte)0x02, info.getRawByte2nd());\r
-\r
- info = list.get(1);\r
- assertEquals(7, info.getCharPosition());\r
- assertTrue(info.has2nd());\r
- assertEquals((byte)0xfe, info.getRawByte1st());\r
- assertEquals((byte)0xff, info.getRawByte2nd());\r
-\r
- return;\r
- }\r
-\r
- /**\r
- * Test of toString method, of class DecodedContent.\r
- */\r
- @Test\r
- public void testToString(){\r
- System.out.println("toString");\r
-\r
- DecodedContent content;\r
-\r
- content = new DecodedContent();\r
- content.append("abc");\r
- content.addDecodeError((byte)0x01, (byte)0x02);\r
- content.append("def");\r
- content.addDecodeError((byte)0xfe, (byte)0xff);\r
-\r
- assertEquals("abc?def?", content.toString());\r
- assertEquals(content.getRawContent().toString(), content.toString());\r
-\r
- return;\r
- }\r
-\r
- /**\r
- * Test of lsearchErrorIndex method, of class DecodedContent.\r
- */\r
- @Test\r
- public void testLsearchErrorIndex(){\r
- System.out.println("lsearchErrorIndex");\r
-\r
- List<DecodeErrorInfo> errList;\r
- int result;\r
-\r
- errList = new ArrayList<DecodeErrorInfo>();\r
- result = DecodedContent.lsearchErrorIndex(errList, 10);\r
- assertEquals(0, result);\r
-\r
- errList.clear();\r
- errList.add(new DecodeErrorInfo(5, (byte)0x00));\r
- result = DecodedContent.lsearchErrorIndex(errList, 10);\r
- assertEquals(1, result);\r
-\r
- errList.clear();\r
- errList.add(new DecodeErrorInfo(10, (byte)0x00));\r
- result = DecodedContent.lsearchErrorIndex(errList, 10);\r
- assertEquals(0, result);\r
-\r
- errList.clear();\r
- errList.add(new DecodeErrorInfo(15, (byte)0x00));\r
- result = DecodedContent.lsearchErrorIndex(errList, 10);\r
- assertEquals(0, result);\r
-\r
- errList.clear();\r
- errList.add(new DecodeErrorInfo(4, (byte)0x00));\r
- errList.add(new DecodeErrorInfo(5, (byte)0x00));\r
- errList.add(new DecodeErrorInfo(14, (byte)0x00));\r
- errList.add(new DecodeErrorInfo(15, (byte)0x00));\r
- result = DecodedContent.lsearchErrorIndex(errList, 10);\r
- assertEquals(2, result);\r
-\r
- errList.clear();\r
- errList.add(new DecodeErrorInfo(4, (byte)0x00));\r
- errList.add(new DecodeErrorInfo(5, (byte)0x00));\r
- errList.add(new DecodeErrorInfo(10, (byte)0x00));\r
- errList.add(new DecodeErrorInfo(14, (byte)0x00));\r
- errList.add(new DecodeErrorInfo(15, (byte)0x00));\r
- result = DecodedContent.lsearchErrorIndex(errList, 10);\r
- assertEquals(2, result);\r
-\r
- return;\r
- }\r
-\r
- /**\r
- * Test of bsearchErrorIndex method, of class DecodedContent.\r
- */\r
- @Test\r
- public void testBsearchErrorIndex(){\r
- System.out.println("bsearchErrorIndex");\r
-\r
- List<DecodeErrorInfo> errList;\r
- int result;\r
-\r
- errList = new ArrayList<DecodeErrorInfo>();\r
- result = DecodedContent.bsearchErrorIndex(errList, 10);\r
- assertEquals(0, result);\r
-\r
- errList.clear();\r
- errList.add(new DecodeErrorInfo(5, (byte)0x00));\r
- result = DecodedContent.bsearchErrorIndex(errList, 10);\r
- assertEquals(1, result);\r
-\r
- errList.clear();\r
- errList.add(new DecodeErrorInfo(10, (byte)0x00));\r
- result = DecodedContent.bsearchErrorIndex(errList, 10);\r
- assertEquals(0, result);\r
-\r
- errList.clear();\r
- errList.add(new DecodeErrorInfo(15, (byte)0x00));\r
- result = DecodedContent.bsearchErrorIndex(errList, 10);\r
- assertEquals(0, result);\r
-\r
- errList.clear();\r
- errList.add(new DecodeErrorInfo(4, (byte)0x00));\r
- errList.add(new DecodeErrorInfo(5, (byte)0x00));\r
- errList.add(new DecodeErrorInfo(14, (byte)0x00));\r
- errList.add(new DecodeErrorInfo(15, (byte)0x00));\r
- result = DecodedContent.bsearchErrorIndex(errList, 10);\r
- assertEquals(2, result);\r
-\r
- errList.clear();\r
- errList.add(new DecodeErrorInfo(4, (byte)0x00));\r
- errList.add(new DecodeErrorInfo(5, (byte)0x00));\r
- errList.add(new DecodeErrorInfo(10, (byte)0x00));\r
- errList.add(new DecodeErrorInfo(14, (byte)0x00));\r
- errList.add(new DecodeErrorInfo(15, (byte)0x00));\r
- result = DecodedContent.bsearchErrorIndex(errList, 10);\r
- assertEquals(2, result);\r
-\r
- return;\r
- }\r
-\r
- /**\r
- * Test of searchErrorIndex method, of class DecodedContent.\r
- */\r
- @Test\r
- public void testSearchErrorIndex(){\r
- System.out.println("searchErrorIndex");\r
-\r
- List<DecodeErrorInfo> errList;\r
- int result;\r
-\r
- errList = new ArrayList<DecodeErrorInfo>();\r
-\r
- errList.clear();\r
- for(int pos = 0; pos <= 1000; pos += 10){\r
- errList.add(new DecodeErrorInfo(pos, (byte)0x00));\r
- }\r
- result = DecodedContent.searchErrorIndex(errList, 503);\r
- assertEquals(51, result);\r
-\r
- errList.clear();\r
- for(int pos = 0; pos <= 50; pos += 10){\r
- errList.add(new DecodeErrorInfo(pos, (byte)0x00));\r
- }\r
- result = DecodedContent.searchErrorIndex(errList, 23);\r
- assertEquals(3, result);\r
-\r
- return;\r
- }\r
-\r
- /**\r
- * Test of appendGappedErrorInfo method, of class DecodedContent.\r
- */\r
- @Test\r
- public void testAppendGappedErrorInfo(){\r
- System.out.println("appendGappedErrorInfo");\r
-\r
- DecodedContent sourceContent;\r
- sourceContent = new DecodedContent();\r
- for(int pos = 0; pos <= 50; pos += 10){\r
- sourceContent.append("123456789");\r
- sourceContent.addDecodeError((byte)0x00);\r
- }\r
-\r
- List<DecodeErrorInfo> result;\r
- result = DecodedContent.appendGappedErrorInfo(sourceContent, 15, 35, null, -100);\r
- assertNotNull(result);\r
- assertEquals(2, result.size());\r
- assertEquals(119, result.get(0).getCharPosition());\r
- assertEquals(129, result.get(1).getCharPosition());\r
-\r
- return;\r
- }\r
-\r
- /**\r
- * Test of ensureCapacity method, of class DecodedContent.\r
- */\r
- @Test\r
- public void testEnsureCapacity(){\r
- System.out.println("ensureCapacity");\r
-\r
- DecodedContent content;\r
- \r
- content = new DecodedContent("abc");\r
- content.ensureCapacity(-1);\r
- content.ensureCapacity(0);\r
- content.ensureCapacity(1);\r
- content.ensureCapacity(5);\r
- content.append("def");\r
- assertEquals("abcdef", content.toString());\r
-\r
- content = new DecodedContent();\r
- content.ensureCapacity(5);\r
- content.append("abc");\r
- assertEquals("abc", content.toString());\r
-\r
- return;\r
- }\r
-\r
- /**\r
- * Test of setCharAt method, of class DecodedContent.\r
- */\r
- @Test\r
- public void testSetCharAt(){\r
- System.out.println("setCharAt");\r
-\r
- DecodedContent content;\r
-\r
- content = new DecodedContent("abc");\r
- content.setCharAt(1, 'B');\r
- assertEquals("aBc", content.toString());\r
-\r
- content = new DecodedContent("a");\r
- content.addDecodeError((byte)0xff);\r
- content.append('c');\r
- assertEquals("a?c", content.toString());\r
- content.setCharAt(1, 'B');\r
- assertEquals("aBc", content.toString());\r
- assertEquals(1, content.getDecodeErrorList().size());\r
- assertEquals(1, content.getDecodeErrorList().get(0).getCharPosition());\r
- assertEquals((byte)0xff, content.getDecodeErrorList().get(0).getRawByte1st());\r
-\r
- content = new DecodedContent("abc");\r
- try{\r
- content.setCharAt(-1, 'B');\r
- fail();\r
- }catch(IndexOutOfBoundsException e){\r
- // NOTHING\r
- }\r
- try{\r
- content.setCharAt(10, 'B');\r
- fail();\r
- }catch(IndexOutOfBoundsException e){\r
- // NOTHING\r
- }\r
-\r
- return;\r
- }\r
-\r
-}\r
+/*
+ * License : The MIT License
+ * Copyright(c) 2009 olyutorskii
+ */
+
+package jp.sourceforge.jindolf.parser;
+
+import java.util.ArrayList;
+import java.util.List;
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import static org.junit.Assert.*;
+
+/**
+ */
+public class DecodedContentTest {
+
+ public DecodedContentTest() {
+ }
+
+ @BeforeClass
+ public static void setUpClass() throws Exception{
+ }
+
+ @AfterClass
+ public static void tearDownClass() throws Exception{
+ }
+
+ @Before
+ public void setUp() {
+ }
+
+ @After
+ public void tearDown() {
+ }
+
+ /**
+ * Test of Constructor, of class DecodedContent.
+ */
+ @Test
+ public void testConstructor(){
+ System.out.println("Constructor");
+
+ DecodedContent content;
+
+ content = new DecodedContent();
+ assertEquals("", content.toString());
+
+ content = new DecodedContent("abc");
+ assertEquals("abc", content.toString());
+
+ content = new DecodedContent(128);
+ assertEquals("", content.toString());
+
+ content = new DecodedContent(0);
+ assertEquals("", content.toString());
+ content.append("abc");
+ assertEquals("abc", content.toString());
+
+ try{
+ content = new DecodedContent(-1);
+ fail();
+ }catch(NegativeArraySizeException e){
+ }catch(Throwable e){
+ fail();
+ }
+
+ return;
+ }
+
+ /**
+ * Test of init method, of class DecodedContent.
+ */
+ @Test
+ public void testInit(){
+ System.out.println("init");
+
+ DecodedContent content;
+
+ content = new DecodedContent();
+ content.append("abc");
+ content.addDecodeError((byte)0xff);
+ content.append("def");
+ assertEquals("abc?def", content.toString());
+ assertEquals(1, content.getDecodeErrorList().size());
+
+ content.init();
+ assertEquals("", content.toString());
+ assertEquals(0, content.getDecodeErrorList().size());
+
+ content.append('X');
+ assertEquals("X", content.toString());
+
+ return;
+ }
+
+ /**
+ * Test of hasDecodeError method, of class DecodedContent.
+ */
+ @Test
+ public void testHasDecodeError(){
+ System.out.println("hasDecodeError");
+
+ DecodedContent content;
+
+ content = new DecodedContent();
+ assertFalse(content.hasDecodeError());
+
+ content.append("a");
+ assertFalse(content.hasDecodeError());
+
+ content.addDecodeError((byte)0xff);
+ assertTrue(content.hasDecodeError());
+
+ content.append("b");
+ assertTrue(content.hasDecodeError());
+
+ content.init();
+ assertFalse(content.hasDecodeError());
+
+ content.append("c");
+ assertFalse(content.hasDecodeError());
+
+ content = new DecodedContent();
+ List list = content.getDecodeErrorList();
+ assertEquals(0, list.size());
+ assertFalse(content.hasDecodeError());
+
+ return;
+ }
+
+ /**
+ * Test of getDecodeErrorList method, of class DecodedContent.
+ */
+ @Test
+ public void testGetDecodeErrorList(){
+ System.out.println("getDecodeErrorList");
+
+ DecodedContent content;
+ List<DecodeErrorInfo> list;
+
+ content = new DecodedContent();
+ list = content.getDecodeErrorList();
+ assertEquals(0, list.size());
+
+ content.append("abc");
+ list = content.getDecodeErrorList();
+ assertEquals(0, list.size());
+
+ content.addDecodeError((byte)0xff);
+ list = content.getDecodeErrorList();
+ assertEquals(1, list.size());
+
+ content.append("def");
+ list = content.getDecodeErrorList();
+ assertEquals(1, list.size());
+
+ content.addDecodeError((byte)0x03, (byte)0x04);
+ list = content.getDecodeErrorList();
+ assertEquals(2, list.size());
+
+ return;
+ }
+
+ /**
+ * Test of getRawContent method, of class DecodedContent.
+ */
+ @Test
+ public void testGetRawContent(){
+ System.out.println("getRawContent");
+
+ DecodedContent content;
+
+ content = new DecodedContent();
+ assertEquals("", content.getRawContent().toString());
+
+ content.append("a");
+ assertEquals("a", content.getRawContent().toString());
+
+ content.addDecodeError((byte)0xff);
+ assertEquals("a?", content.getRawContent().toString());
+
+ content.append("b");
+ assertEquals("a?b", content.getRawContent().toString());
+
+ assertEquals(content.toString(), content.getRawContent().toString());
+
+ return;
+ }
+
+ /**
+ * Test of charAt method, of class DecodedContent.
+ */
+ @Test
+ public void testCharAt(){
+ System.out.println("charAt");
+
+ DecodedContent content;
+
+ content = new DecodedContent();
+ content.append("12345");
+ assertEquals('1', content.charAt(0));
+ assertEquals('3', content.charAt(2));
+ assertEquals('5', content.charAt(4));
+
+ try{
+ content.charAt(-1);
+ fail();
+ }catch(IndexOutOfBoundsException e){
+ }catch(Throwable e){
+ fail();
+ }
+
+ try{
+ content.charAt(5);
+ fail();
+ }catch(IndexOutOfBoundsException e){
+ }catch(Throwable e){
+ fail();
+ }
+
+ return;
+ }
+
+ /**
+ * Test of length method, of class DecodedContent.
+ */
+ @Test
+ public void testLength(){
+ System.out.println("length");
+
+ DecodedContent content;
+
+ content = new DecodedContent();
+ assertEquals(0, content.length());
+
+ content.append("12345");
+ assertEquals(5, content.length());
+
+ content.addDecodeError((byte)0xff);
+ assertEquals(6, content.length());
+
+ content.init();
+ assertEquals(0, content.length());
+
+ return;
+ }
+
+ /**
+ * Test of subSequence method, of class DecodedContent.
+ */
+ @Test
+ public void testSubSequence(){
+ System.out.println("subSequence");
+
+ DecodedContent content;
+
+ content = new DecodedContent();
+
+ content.append("12345");
+ assertEquals("234", content.subSequence(1, 4).toString());
+
+ try{
+ content.subSequence(-1, 4);
+ fail();
+ }catch(IndexOutOfBoundsException e){
+ }catch(Throwable e){
+ fail();
+ }
+
+ try{
+ content.subSequence(1, 6);
+ fail();
+ }catch(IndexOutOfBoundsException e){
+ }catch(Throwable e){
+ fail();
+ }
+
+ try{
+ content.subSequence(4, 1);
+ fail();
+ }catch(IndexOutOfBoundsException e){
+ }catch(Throwable e){
+ fail();
+ }
+
+ return;
+ }
+
+ /**
+ * Test of subContent method, of class DecodedContent.
+ */
+ @Test
+ public void testSubContent(){
+ System.out.println("subContent");
+
+ DecodedContent content;
+
+ content = new DecodedContent();
+
+ content.append("12345");
+ assertEquals("234", content.subContent(1, 4).toString());
+
+ try{
+ content.subContent(-1, 4);
+ fail();
+ }catch(IndexOutOfBoundsException e){
+ }catch(Throwable e){
+ fail();
+ }
+
+ try{
+ content.subContent(1, 6);
+ fail();
+ }catch(IndexOutOfBoundsException e){
+ }catch(Throwable e){
+ fail();
+ }
+
+ try{
+ content.subContent(4, 1);
+ fail();
+ }catch(IndexOutOfBoundsException e){
+ }catch(Throwable e){
+ fail();
+ }
+
+ content = new DecodedContent();
+ content.append("ab");
+ content.addDecodeError((byte)0x01);
+ content.append("de");
+ content = content.subContent(1,4);
+ assertEquals("b?d", content.toString());
+
+ List<DecodeErrorInfo> list = content.getDecodeErrorList();
+ assertEquals(1, list.size());
+ assertEquals((byte)0x01, list.get(0).getRawByte1st());
+
+ return;
+ }
+
+ /**
+ * Test of append method, of class DecodedContent.
+ */
+ @Test
+ public void testAppend_char(){
+ System.out.println("append");
+
+ DecodedContent content;
+
+ content = new DecodedContent();
+ content.append('a');
+ assertEquals("a", content.toString());
+
+ return;
+ }
+
+ /**
+ * Test of append method, of class DecodedContent.
+ */
+ @Test
+ public void testAppend_CharSequence(){
+ System.out.println("append");
+
+ DecodedContent content;
+
+ content = new DecodedContent();
+ CharSequence seq = "abc";
+ content.append(seq);
+ assertEquals("abc", content.toString());
+
+ return;
+ }
+
+ /**
+ * Test of append method, of class DecodedContent.
+ */
+ @Test
+ public void testAppend_3args_1(){
+ System.out.println("append");
+
+ DecodedContent content;
+
+ content = new DecodedContent();
+ content.append("abc");
+ assertEquals("abc", content.toString());
+
+ CharSequence seq = "12345";
+ content.append(seq, 1, 4);
+ assertEquals("abc234", content.toString());
+
+ return;
+ }
+
+ /**
+ * Test of append method, of class DecodedContent.
+ */
+ @Test
+ public void testAppend_3args_2(){
+ System.out.println("append");
+
+ DecodedContent content;
+
+ content = new DecodedContent();
+ content.append("abc");
+
+ DecodedContent other;
+ other = new DecodedContent();
+ other.append("12345");
+
+ content.append(other, 1, 4);
+ assertEquals("abc234", content.toString());
+
+ content = new DecodedContent();
+ content.append("abc");
+
+ other = new DecodedContent();
+ other.addDecodeError((byte)0x01);
+ other.addDecodeError((byte)0x02);
+ other.addDecodeError((byte)0x03);
+ other.addDecodeError((byte)0x04);
+ other.addDecodeError((byte)0x05);
+
+ content.append(other, 1, 4);
+ assertEquals("abc???", content.toString());
+
+ List<DecodeErrorInfo> list = content.getDecodeErrorList();
+ assertEquals(3, list.size());
+
+ DecodeErrorInfo info;
+
+ info = list.get(0);
+ assertEquals(3, info.getCharPosition());
+ assertEquals((byte)0x02, info.getRawByte1st());
+ info = list.get(1);
+ assertEquals(4, info.getCharPosition());
+ assertEquals((byte)0x03, info.getRawByte1st());
+ info = list.get(2);
+ assertEquals(5, info.getCharPosition());
+ assertEquals((byte)0x04, info.getRawByte1st());
+
+ return;
+ }
+
+ /**
+ * Test of addDecodeError method, of class DecodedContent.
+ */
+ @Test
+ public void testAddDecodeError_byte(){
+ System.out.println("addDecodeError");
+
+ DecodedContent content;
+
+ content = new DecodedContent();
+ content.append("abc");
+ content.addDecodeError((byte)0xfe);
+ content.append("def");
+ content.addDecodeError((byte)0xff);
+
+ assertEquals("abc?def?", content.toString());
+ List<DecodeErrorInfo> list = content.getDecodeErrorList();
+ assertEquals(2, list.size());
+
+ DecodeErrorInfo info;
+
+ info = list.get(0);
+ assertEquals(3, list.get(0).getCharPosition());
+ assertFalse(info.has2nd());
+ assertEquals((byte)0xfe, info.getRawByte1st());
+
+ info = list.get(1);
+ assertEquals(7, info.getCharPosition());
+ assertFalse(info.has2nd());
+ assertEquals((byte)0xff, info.getRawByte1st());
+
+ return;
+ }
+
+ /**
+ * Test of addDecodeError method, of class DecodedContent.
+ */
+ @Test
+ public void testAddDecodeError_byte_byte(){
+ System.out.println("addDecodeError");
+
+ DecodedContent content;
+
+ content = new DecodedContent();
+ content.append("abc");
+ content.addDecodeError((byte)0x01, (byte)0x02);
+ content.append("def");
+ content.addDecodeError((byte)0xfe, (byte)0xff);
+
+ assertEquals("abc?def?", content.toString());
+ List<DecodeErrorInfo> list = content.getDecodeErrorList();
+ assertEquals(2, list.size());
+
+ DecodeErrorInfo info;
+
+ info = list.get(0);
+ assertEquals(3, list.get(0).getCharPosition());
+ assertTrue(info.has2nd());
+ assertEquals((byte)0x01, info.getRawByte1st());
+ assertEquals((byte)0x02, info.getRawByte2nd());
+
+ info = list.get(1);
+ assertEquals(7, info.getCharPosition());
+ assertTrue(info.has2nd());
+ assertEquals((byte)0xfe, info.getRawByte1st());
+ assertEquals((byte)0xff, info.getRawByte2nd());
+
+ return;
+ }
+
+ /**
+ * Test of toString method, of class DecodedContent.
+ */
+ @Test
+ public void testToString(){
+ System.out.println("toString");
+
+ DecodedContent content;
+
+ content = new DecodedContent();
+ content.append("abc");
+ content.addDecodeError((byte)0x01, (byte)0x02);
+ content.append("def");
+ content.addDecodeError((byte)0xfe, (byte)0xff);
+
+ assertEquals("abc?def?", content.toString());
+ assertEquals(content.getRawContent().toString(), content.toString());
+
+ return;
+ }
+
+ /**
+ * Test of lsearchErrorIndex method, of class DecodedContent.
+ */
+ @Test
+ public void testLsearchErrorIndex(){
+ System.out.println("lsearchErrorIndex");
+
+ List<DecodeErrorInfo> errList;
+ int result;
+
+ errList = new ArrayList<DecodeErrorInfo>();
+ result = DecodedContent.lsearchErrorIndex(errList, 10);
+ assertEquals(0, result);
+
+ errList.clear();
+ errList.add(new DecodeErrorInfo(5, (byte)0x00));
+ result = DecodedContent.lsearchErrorIndex(errList, 10);
+ assertEquals(1, result);
+
+ errList.clear();
+ errList.add(new DecodeErrorInfo(10, (byte)0x00));
+ result = DecodedContent.lsearchErrorIndex(errList, 10);
+ assertEquals(0, result);
+
+ errList.clear();
+ errList.add(new DecodeErrorInfo(15, (byte)0x00));
+ result = DecodedContent.lsearchErrorIndex(errList, 10);
+ assertEquals(0, result);
+
+ errList.clear();
+ errList.add(new DecodeErrorInfo(4, (byte)0x00));
+ errList.add(new DecodeErrorInfo(5, (byte)0x00));
+ errList.add(new DecodeErrorInfo(14, (byte)0x00));
+ errList.add(new DecodeErrorInfo(15, (byte)0x00));
+ result = DecodedContent.lsearchErrorIndex(errList, 10);
+ assertEquals(2, result);
+
+ errList.clear();
+ errList.add(new DecodeErrorInfo(4, (byte)0x00));
+ errList.add(new DecodeErrorInfo(5, (byte)0x00));
+ errList.add(new DecodeErrorInfo(10, (byte)0x00));
+ errList.add(new DecodeErrorInfo(14, (byte)0x00));
+ errList.add(new DecodeErrorInfo(15, (byte)0x00));
+ result = DecodedContent.lsearchErrorIndex(errList, 10);
+ assertEquals(2, result);
+
+ return;
+ }
+
+ /**
+ * Test of bsearchErrorIndex method, of class DecodedContent.
+ */
+ @Test
+ public void testBsearchErrorIndex(){
+ System.out.println("bsearchErrorIndex");
+
+ List<DecodeErrorInfo> errList;
+ int result;
+
+ errList = new ArrayList<DecodeErrorInfo>();
+ result = DecodedContent.bsearchErrorIndex(errList, 10);
+ assertEquals(0, result);
+
+ errList.clear();
+ errList.add(new DecodeErrorInfo(5, (byte)0x00));
+ result = DecodedContent.bsearchErrorIndex(errList, 10);
+ assertEquals(1, result);
+
+ errList.clear();
+ errList.add(new DecodeErrorInfo(10, (byte)0x00));
+ result = DecodedContent.bsearchErrorIndex(errList, 10);
+ assertEquals(0, result);
+
+ errList.clear();
+ errList.add(new DecodeErrorInfo(15, (byte)0x00));
+ result = DecodedContent.bsearchErrorIndex(errList, 10);
+ assertEquals(0, result);
+
+ errList.clear();
+ errList.add(new DecodeErrorInfo(4, (byte)0x00));
+ errList.add(new DecodeErrorInfo(5, (byte)0x00));
+ errList.add(new DecodeErrorInfo(14, (byte)0x00));
+ errList.add(new DecodeErrorInfo(15, (byte)0x00));
+ result = DecodedContent.bsearchErrorIndex(errList, 10);
+ assertEquals(2, result);
+
+ errList.clear();
+ errList.add(new DecodeErrorInfo(4, (byte)0x00));
+ errList.add(new DecodeErrorInfo(5, (byte)0x00));
+ errList.add(new DecodeErrorInfo(10, (byte)0x00));
+ errList.add(new DecodeErrorInfo(14, (byte)0x00));
+ errList.add(new DecodeErrorInfo(15, (byte)0x00));
+ result = DecodedContent.bsearchErrorIndex(errList, 10);
+ assertEquals(2, result);
+
+ return;
+ }
+
+ /**
+ * Test of searchErrorIndex method, of class DecodedContent.
+ */
+ @Test
+ public void testSearchErrorIndex(){
+ System.out.println("searchErrorIndex");
+
+ List<DecodeErrorInfo> errList;
+ int result;
+
+ errList = new ArrayList<DecodeErrorInfo>();
+
+ errList.clear();
+ for(int pos = 0; pos <= 1000; pos += 10){
+ errList.add(new DecodeErrorInfo(pos, (byte)0x00));
+ }
+ result = DecodedContent.searchErrorIndex(errList, 503);
+ assertEquals(51, result);
+
+ errList.clear();
+ for(int pos = 0; pos <= 50; pos += 10){
+ errList.add(new DecodeErrorInfo(pos, (byte)0x00));
+ }
+ result = DecodedContent.searchErrorIndex(errList, 23);
+ assertEquals(3, result);
+
+ return;
+ }
+
+ /**
+ * Test of appendGappedErrorInfo method, of class DecodedContent.
+ */
+ @Test
+ public void testAppendGappedErrorInfo(){
+ System.out.println("appendGappedErrorInfo");
+
+ DecodedContent sourceContent;
+ sourceContent = new DecodedContent();
+ for(int pos = 0; pos <= 50; pos += 10){
+ sourceContent.append("123456789");
+ sourceContent.addDecodeError((byte)0x00);
+ }
+
+ List<DecodeErrorInfo> result;
+ result = DecodedContent.appendGappedErrorInfo(sourceContent, 15, 35, null, -100);
+ assertNotNull(result);
+ assertEquals(2, result.size());
+ assertEquals(119, result.get(0).getCharPosition());
+ assertEquals(129, result.get(1).getCharPosition());
+
+ return;
+ }
+
+ /**
+ * Test of ensureCapacity method, of class DecodedContent.
+ */
+ @Test
+ public void testEnsureCapacity(){
+ System.out.println("ensureCapacity");
+
+ DecodedContent content;
+
+ content = new DecodedContent("abc");
+ content.ensureCapacity(-1);
+ content.ensureCapacity(0);
+ content.ensureCapacity(1);
+ content.ensureCapacity(5);
+ content.append("def");
+ assertEquals("abcdef", content.toString());
+
+ content = new DecodedContent();
+ content.ensureCapacity(5);
+ content.append("abc");
+ assertEquals("abc", content.toString());
+
+ return;
+ }
+
+ /**
+ * Test of setCharAt method, of class DecodedContent.
+ */
+ @Test
+ public void testSetCharAt(){
+ System.out.println("setCharAt");
+
+ DecodedContent content;
+
+ content = new DecodedContent("abc");
+ content.setCharAt(1, 'B');
+ assertEquals("aBc", content.toString());
+
+ content = new DecodedContent("a");
+ content.addDecodeError((byte)0xff);
+ content.append('c');
+ assertEquals("a?c", content.toString());
+ content.setCharAt(1, 'B');
+ assertEquals("aBc", content.toString());
+ assertEquals(1, content.getDecodeErrorList().size());
+ assertEquals(1, content.getDecodeErrorList().get(0).getCharPosition());
+ assertEquals((byte)0xff, content.getDecodeErrorList().get(0).getRawByte1st());
+
+ content = new DecodedContent("abc");
+ try{
+ content.setCharAt(-1, 'B');
+ fail();
+ }catch(IndexOutOfBoundsException e){
+ // NOTHING
+ }
+ try{
+ content.setCharAt(10, 'B');
+ fail();
+ }catch(IndexOutOfBoundsException e){
+ // NOTHING
+ }
+
+ return;
+ }
+
+}
-/*\r
- * License : The MIT License\r
- * Copyright(c) 2009 olyutorskii\r
- */\r
-\r
-package jp.sourceforge.jindolf.parser;\r
-\r
-import java.util.List;\r
-import org.junit.After;\r
-import org.junit.AfterClass;\r
-import org.junit.Before;\r
-import org.junit.BeforeClass;\r
-import org.junit.Test;\r
-import static org.junit.Assert.*;\r
-\r
-/**\r
- */\r
-public class EntityConverterTest {\r
-\r
- public EntityConverterTest() {\r
- }\r
-\r
- @BeforeClass\r
- public static void setUpClass() throws Exception{\r
- }\r
-\r
- @AfterClass\r
- public static void tearDownClass() throws Exception{\r
- }\r
-\r
- @Before\r
- public void setUp() {\r
- }\r
-\r
- @After\r
- public void tearDown() {\r
- }\r
-\r
- /**\r
- * Test of convert method, of class EntityConverter.\r
- */\r
- @Test\r
- public void testConvert(){\r
- System.out.println("convert");\r
-\r
- EntityConverter converter = new EntityConverter();\r
-\r
- DecodedContent from;\r
- DecodedContent result;\r
-\r
- from = new DecodedContent();\r
- from.append("a>b<c"d&e");\r
- result = converter.convert(from, 0, from.length());\r
- assertEquals("a>b<c\"d&e", result.toString());\r
-\r
- from = new DecodedContent();\r
- from.append("><"&");\r
- result = converter.convert(from, 0, from.length());\r
- assertEquals("><\"&", result.toString());\r
-\r
- from = new DecodedContent();\r
- from.append("12345");\r
- result = converter.convert(from, 1, 3);\r
- assertEquals("23", result.toString());\r
-\r
- from = new DecodedContent();\r
- from.append("12>45");\r
- result = converter.convert(from, 1, 7);\r
- assertEquals("2>4", result.toString());\r
-\r
- from = new DecodedContent();\r
- from.append("12>45");\r
- result = converter.convert(from, 3, 7);\r
- assertEquals("gt;4", result.toString());\r
-\r
- from = new DecodedContent();\r
- from.append("&gt;");\r
- result = converter.convert(from, 0, from.length());\r
- assertEquals(">", result.toString());\r
-\r
- from = new DecodedContent();\r
- from.append("a>b");\r
- result = converter.convert(from);\r
- assertEquals("a>b", result.toString());\r
-\r
- from = new DecodedContent();\r
- from.append("a>b");\r
- from.addDecodeError((byte)0x03);\r
- from.append("c");\r
- result = converter.convert(from);\r
- assertEquals("a>b?c", result.toString());\r
- assertTrue(result.hasDecodeError());\r
- List<DecodeErrorInfo> list = result.getDecodeErrorList();\r
- assertEquals(1, list.size());\r
- assertEquals((byte)0x03, list.get(0).getRawByte1st());\r
-\r
- from = new DecodedContent();\r
- from.append("");\r
- result = converter.convert(from, 0, 0);\r
- assertEquals("", result.toString());\r
-\r
- from = new DecodedContent();\r
- from.append("a\\b");\r
- result = converter.convert(from, 0, from.length());\r
- assertEquals("a¥b", result.toString());\r
-\r
- from = new DecodedContent();\r
- from.append("abcde");\r
- SeqRange range = new SeqRange(1,4);\r
- result = converter.convert(from, range);\r
- assertEquals("bcd", result.toString());\r
-\r
- return;\r
- }\r
-\r
- /**\r
- * Test of append method, of class EntityConverter.\r
- */\r
- @Test\r
- public void testAppend(){\r
- System.out.println("append");\r
-\r
- EntityConverter converter = new EntityConverter();\r
- DecodedContent target;\r
- DecodedContent from;\r
- DecodedContent result;\r
-\r
- target = new DecodedContent("abc");\r
- from = new DecodedContent("d>f");\r
- result = converter.append(target,from);\r
- assertEquals("abcd>f", result.toString());\r
-\r
- target = new DecodedContent("abc");\r
- from = new DecodedContent("d>fg<i");\r
- result = converter.append(target, from, 6, 12);\r
- assertEquals("abcg<i", result.toString());\r
-\r
- target = new DecodedContent("abc");\r
- from = new DecodedContent("d>fg<i");\r
- result = converter.append(target, from, new SeqRange(6, 12));\r
- assertEquals("abcg<i", result.toString());\r
-\r
- target = new DecodedContent();\r
- target.append('a');\r
- target.addDecodeError((byte)0xff);\r
- target.append('c');\r
- from = new DecodedContent();\r
- from.append('d');\r
- from.addDecodeError((byte)0xfe);\r
- from.append('f');\r
- result = converter.append(target, from);\r
- assertEquals("a?cd?f", result.toString());\r
- assertTrue(result.hasDecodeError());\r
- List<DecodeErrorInfo> list = result.getDecodeErrorList();\r
- assertEquals(2, list.size());\r
- assertEquals((byte)0xff, list.get(0).getRawByte1st());\r
- assertEquals((byte)0xfe, list.get(1).getRawByte1st());\r
- assertEquals(1, list.get(0).getCharPosition());\r
- assertEquals(4, list.get(1).getCharPosition());\r
-\r
- return;\r
- }\r
-\r
-}\r
+/*
+ * License : The MIT License
+ * Copyright(c) 2009 olyutorskii
+ */
+
+package jp.sourceforge.jindolf.parser;
+
+import java.util.List;
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import static org.junit.Assert.*;
+
+/**
+ */
+public class EntityConverterTest {
+
+ public EntityConverterTest() {
+ }
+
+ @BeforeClass
+ public static void setUpClass() throws Exception{
+ }
+
+ @AfterClass
+ public static void tearDownClass() throws Exception{
+ }
+
+ @Before
+ public void setUp() {
+ }
+
+ @After
+ public void tearDown() {
+ }
+
+ /**
+ * Test of convert method, of class EntityConverter.
+ */
+ @Test
+ public void testConvert(){
+ System.out.println("convert");
+
+ EntityConverter converter = new EntityConverter();
+
+ DecodedContent from;
+ DecodedContent result;
+
+ from = new DecodedContent();
+ from.append("a>b<c"d&e");
+ result = converter.convert(from, 0, from.length());
+ assertEquals("a>b<c\"d&e", result.toString());
+
+ from = new DecodedContent();
+ from.append("><"&");
+ result = converter.convert(from, 0, from.length());
+ assertEquals("><\"&", result.toString());
+
+ from = new DecodedContent();
+ from.append("12345");
+ result = converter.convert(from, 1, 3);
+ assertEquals("23", result.toString());
+
+ from = new DecodedContent();
+ from.append("12>45");
+ result = converter.convert(from, 1, 7);
+ assertEquals("2>4", result.toString());
+
+ from = new DecodedContent();
+ from.append("12>45");
+ result = converter.convert(from, 3, 7);
+ assertEquals("gt;4", result.toString());
+
+ from = new DecodedContent();
+ from.append("&gt;");
+ result = converter.convert(from, 0, from.length());
+ assertEquals(">", result.toString());
+
+ from = new DecodedContent();
+ from.append("a>b");
+ result = converter.convert(from);
+ assertEquals("a>b", result.toString());
+
+ from = new DecodedContent();
+ from.append("a>b");
+ from.addDecodeError((byte)0x03);
+ from.append("c");
+ result = converter.convert(from);
+ assertEquals("a>b?c", result.toString());
+ assertTrue(result.hasDecodeError());
+ List<DecodeErrorInfo> list = result.getDecodeErrorList();
+ assertEquals(1, list.size());
+ assertEquals((byte)0x03, list.get(0).getRawByte1st());
+
+ from = new DecodedContent();
+ from.append("");
+ result = converter.convert(from, 0, 0);
+ assertEquals("", result.toString());
+
+ from = new DecodedContent();
+ from.append("a\\b");
+ result = converter.convert(from, 0, from.length());
+ assertEquals("a¥b", result.toString());
+
+ from = new DecodedContent();
+ from.append("abcde");
+ SeqRange range = new SeqRange(1,4);
+ result = converter.convert(from, range);
+ assertEquals("bcd", result.toString());
+
+ return;
+ }
+
+ /**
+ * Test of append method, of class EntityConverter.
+ */
+ @Test
+ public void testAppend(){
+ System.out.println("append");
+
+ EntityConverter converter = new EntityConverter();
+ DecodedContent target;
+ DecodedContent from;
+ DecodedContent result;
+
+ target = new DecodedContent("abc");
+ from = new DecodedContent("d>f");
+ result = converter.append(target,from);
+ assertEquals("abcd>f", result.toString());
+
+ target = new DecodedContent("abc");
+ from = new DecodedContent("d>fg<i");
+ result = converter.append(target, from, 6, 12);
+ assertEquals("abcg<i", result.toString());
+
+ target = new DecodedContent("abc");
+ from = new DecodedContent("d>fg<i");
+ result = converter.append(target, from, new SeqRange(6, 12));
+ assertEquals("abcg<i", result.toString());
+
+ target = new DecodedContent();
+ target.append('a');
+ target.addDecodeError((byte)0xff);
+ target.append('c');
+ from = new DecodedContent();
+ from.append('d');
+ from.addDecodeError((byte)0xfe);
+ from.append('f');
+ result = converter.append(target, from);
+ assertEquals("a?cd?f", result.toString());
+ assertTrue(result.hasDecodeError());
+ List<DecodeErrorInfo> list = result.getDecodeErrorList();
+ assertEquals(2, list.size());
+ assertEquals((byte)0xff, list.get(0).getRawByte1st());
+ assertEquals((byte)0xfe, list.get(1).getRawByte1st());
+ assertEquals(1, list.get(0).getCharPosition());
+ assertEquals(4, list.get(1).getCharPosition());
+
+ return;
+ }
+
+}
-/*\r
- * License : The MIT License\r
- * Copyright(c) 2009 olyutorskii\r
- */\r
-\r
-package jp.sourceforge.jindolf.parser;\r
-\r
-import org.junit.After;\r
-import org.junit.AfterClass;\r
-import org.junit.Before;\r
-import org.junit.BeforeClass;\r
-import org.junit.Test;\r
-import static org.junit.Assert.*;\r
-\r
-/**\r
- */\r
-public class HtmlParseExceptionTest {\r
-\r
- public HtmlParseExceptionTest() {\r
- }\r
-\r
- @BeforeClass\r
- public static void setUpClass() throws Exception{\r
- }\r
-\r
- @AfterClass\r
- public static void tearDownClass() throws Exception{\r
- }\r
-\r
- @Before\r
- public void setUp() {\r
- }\r
-\r
- @After\r
- public void tearDown() {\r
- }\r
-\r
- /**\r
- * Test of getCharPos method, of class HtmlParseException.\r
- */\r
- @Test\r
- public void testGetCharPos(){\r
- System.out.println("getCharPos");\r
-\r
- HtmlParseException ex;\r
-\r
- ex = new HtmlParseException();\r
- assertTrue(0 > ex.getCharPos());\r
-\r
- ex = new HtmlParseException("abc");\r
- assertTrue(0 > ex.getCharPos());\r
-\r
- ex = new HtmlParseException(99);\r
- assertEquals(99, ex.getCharPos());\r
-\r
- ex = new HtmlParseException("abc", 99);\r
- assertEquals(99, ex.getCharPos());\r
-\r
- return;\r
- }\r
-\r
- /**\r
- * Test of getMessage method, of class HtmlParseException.\r
- */\r
- @Test\r
- public void testGetMessage(){\r
- System.out.println("getMessage");\r
-\r
- HtmlParseException ex;\r
-\r
- ex = new HtmlParseException();\r
- assertEquals("charPos=-1", ex.getMessage());\r
-\r
- ex = new HtmlParseException("abc");\r
- assertEquals("abc charPos=-1", ex.getMessage());\r
-\r
- ex = new HtmlParseException(99);\r
- assertEquals("charPos=99", ex.getMessage());\r
-\r
- ex = new HtmlParseException("abc", 99);\r
- assertEquals("abc charPos=99", ex.getMessage());\r
-\r
- return;\r
- }\r
-\r
-}\r
+/*
+ * License : The MIT License
+ * Copyright(c) 2009 olyutorskii
+ */
+
+package jp.sourceforge.jindolf.parser;
+
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import static org.junit.Assert.*;
+
+/**
+ */
+public class HtmlParseExceptionTest {
+
+ public HtmlParseExceptionTest() {
+ }
+
+ @BeforeClass
+ public static void setUpClass() throws Exception{
+ }
+
+ @AfterClass
+ public static void tearDownClass() throws Exception{
+ }
+
+ @Before
+ public void setUp() {
+ }
+
+ @After
+ public void tearDown() {
+ }
+
+ /**
+ * Test of getCharPos method, of class HtmlParseException.
+ */
+ @Test
+ public void testGetCharPos(){
+ System.out.println("getCharPos");
+
+ HtmlParseException ex;
+
+ ex = new HtmlParseException();
+ assertTrue(0 > ex.getCharPos());
+
+ ex = new HtmlParseException("abc");
+ assertTrue(0 > ex.getCharPos());
+
+ ex = new HtmlParseException(99);
+ assertEquals(99, ex.getCharPos());
+
+ ex = new HtmlParseException("abc", 99);
+ assertEquals(99, ex.getCharPos());
+
+ return;
+ }
+
+ /**
+ * Test of getMessage method, of class HtmlParseException.
+ */
+ @Test
+ public void testGetMessage(){
+ System.out.println("getMessage");
+
+ HtmlParseException ex;
+
+ ex = new HtmlParseException();
+ assertEquals("charPos=-1", ex.getMessage());
+
+ ex = new HtmlParseException("abc");
+ assertEquals("abc charPos=-1", ex.getMessage());
+
+ ex = new HtmlParseException(99);
+ assertEquals("charPos=99", ex.getMessage());
+
+ ex = new HtmlParseException("abc", 99);
+ assertEquals("abc charPos=99", ex.getMessage());
+
+ return;
+ }
+
+}
-/*\r
- * License : The MIT License\r
- * Copyright(c) 2009 olyutorskii\r
- */\r
-\r
-package jp.sourceforge.jindolf.parser;\r
-\r
-import java.io.UnsupportedEncodingException;\r
-import org.junit.After;\r
-import org.junit.AfterClass;\r
-import org.junit.Before;\r
-import org.junit.BeforeClass;\r
-import org.junit.Test;\r
-import static org.junit.Assert.*;\r
-\r
-/**\r
- */\r
-public class ShiftJisTest {\r
-\r
- public ShiftJisTest() {\r
- }\r
-\r
- @BeforeClass\r
- public static void setUpClass() throws Exception{\r
- }\r
-\r
- @AfterClass\r
- public static void tearDownClass() throws Exception{\r
- }\r
-\r
- @Before\r
- public void setUp() {\r
- }\r
-\r
- @After\r
- public void tearDown() {\r
- }\r
-\r
- /**\r
- * Test of isShiftJIS1stByte method, of class ShiftJis.\r
- */\r
- @Test\r
- public void testIsShiftJIS1stByte(){\r
- System.out.println("isShiftJIS1stByte");\r
-\r
- for(int ival=0x00; ival <= 0x80; ival++){\r
- byte bval = (byte)ival;\r
- assertFalse(ShiftJis.isShiftJIS1stByte(bval));\r
- }\r
-\r
- for(int ival=0x81; ival <= 0x9f; ival++){\r
- byte bval = (byte)ival;\r
- assertTrue(ShiftJis.isShiftJIS1stByte(bval));\r
- }\r
-\r
- for(int ival=0xa0; ival <= 0xdf; ival++){\r
- byte bval = (byte)ival;\r
- assertFalse(ShiftJis.isShiftJIS1stByte(bval));\r
- }\r
-\r
- for(int ival=0xe0; ival <= 0xfc; ival++){\r
- byte bval = (byte)ival;\r
- assertTrue(ShiftJis.isShiftJIS1stByte(bval));\r
- }\r
-\r
- for(int ival=0xfd; ival <= 0xff; ival++){\r
- byte bval = (byte)ival;\r
- assertFalse(ShiftJis.isShiftJIS1stByte(bval));\r
- }\r
-\r
- byte[] array;\r
- try{\r
- // 全角スペース\r
- array = "\u3000".getBytes("Shift_JIS");\r
- assertTrue(ShiftJis.isShiftJIS1stByte(array[0]));\r
- // 「熙」\r
- array = "\u7199".getBytes("Shift_JIS");\r
- assertTrue(ShiftJis.isShiftJIS1stByte(array[0]));\r
- // 「"」\r
- array = "\uff02".getBytes("Windows-31J");\r
- assertTrue(ShiftJis.isShiftJIS1stByte(array[0]));\r
- }catch(UnsupportedEncodingException e){\r
- fail();\r
- }\r
-\r
- return;\r
- }\r
-\r
- /**\r
- * Test of isShiftJIS2ndByte method, of class ShiftJis.\r
- */\r
- @Test\r
- public void testIsShiftJIS2ndByte(){\r
- System.out.println("isShiftJIS2ndByte");\r
-\r
- for(int ival=0x00; ival <= 0x3f; ival++){\r
- byte bval = (byte)ival;\r
- assertFalse(ShiftJis.isShiftJIS2ndByte(bval));\r
- }\r
-\r
- for(int ival=0x40; ival <= 0x7e; ival++){\r
- byte bval = (byte)ival;\r
- assertTrue(ShiftJis.isShiftJIS2ndByte(bval));\r
- }\r
-\r
- for(int ival=0x7f; ival <= 0x7f; ival++){\r
- byte bval = (byte)ival;\r
- assertFalse(ShiftJis.isShiftJIS2ndByte(bval));\r
- }\r
-\r
- for(int ival=0x80; ival <= 0xfc; ival++){\r
- byte bval = (byte)ival;\r
- assertTrue(ShiftJis.isShiftJIS2ndByte(bval));\r
- }\r
-\r
- for(int ival=0xfd; ival <= 0xff; ival++){\r
- byte bval = (byte)ival;\r
- assertFalse(ShiftJis.isShiftJIS2ndByte(bval));\r
- }\r
-\r
- byte[] array;\r
- try{\r
- // 全角スペース\r
- array = "\u3000".getBytes("Shift_JIS");\r
- assertTrue(ShiftJis.isShiftJIS2ndByte(array[1]));\r
- // 「熙」\r
- array = "\u7199".getBytes("Shift_JIS");\r
- assertTrue(ShiftJis.isShiftJIS2ndByte(array[1]));\r
- // 「"」\r
- array = "\uff02".getBytes("Windows-31J");\r
- assertTrue(ShiftJis.isShiftJIS2ndByte(array[1]));\r
- }catch(UnsupportedEncodingException e){\r
- fail();\r
- }\r
-\r
- return;\r
- }\r
-\r
- /**\r
- * Test of isShiftJIS method, of class ShiftJis.\r
- */\r
- @Test\r
- public void testIsShiftJIS(){\r
- System.out.println("isShiftJIS");\r
-\r
- byte[] array;\r
- try{\r
- // 全角スペース\r
- array = "\u3000".getBytes("Shift_JIS");\r
- assertTrue(ShiftJis.isShiftJIS(array[0], array[1]));\r
- // 「熙」\r
- array = "\u7199".getBytes("Shift_JIS");\r
- assertTrue(ShiftJis.isShiftJIS(array[0], array[1]));\r
- // 「"」\r
- array = "\uff02".getBytes("Windows-31J");\r
- assertTrue(ShiftJis.isShiftJIS(array[0], array[1]));\r
- }catch(UnsupportedEncodingException e){\r
- fail();\r
- }\r
-\r
- return;\r
- }\r
-\r
-}\r
+/*
+ * License : The MIT License
+ * Copyright(c) 2009 olyutorskii
+ */
+
+package jp.sourceforge.jindolf.parser;
+
+import java.io.UnsupportedEncodingException;
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import static org.junit.Assert.*;
+
+/**
+ */
+public class ShiftJisTest {
+
+ public ShiftJisTest() {
+ }
+
+ @BeforeClass
+ public static void setUpClass() throws Exception{
+ }
+
+ @AfterClass
+ public static void tearDownClass() throws Exception{
+ }
+
+ @Before
+ public void setUp() {
+ }
+
+ @After
+ public void tearDown() {
+ }
+
+ /**
+ * Test of isShiftJIS1stByte method, of class ShiftJis.
+ */
+ @Test
+ public void testIsShiftJIS1stByte(){
+ System.out.println("isShiftJIS1stByte");
+
+ for(int ival=0x00; ival <= 0x80; ival++){
+ byte bval = (byte)ival;
+ assertFalse(ShiftJis.isShiftJIS1stByte(bval));
+ }
+
+ for(int ival=0x81; ival <= 0x9f; ival++){
+ byte bval = (byte)ival;
+ assertTrue(ShiftJis.isShiftJIS1stByte(bval));
+ }
+
+ for(int ival=0xa0; ival <= 0xdf; ival++){
+ byte bval = (byte)ival;
+ assertFalse(ShiftJis.isShiftJIS1stByte(bval));
+ }
+
+ for(int ival=0xe0; ival <= 0xfc; ival++){
+ byte bval = (byte)ival;
+ assertTrue(ShiftJis.isShiftJIS1stByte(bval));
+ }
+
+ for(int ival=0xfd; ival <= 0xff; ival++){
+ byte bval = (byte)ival;
+ assertFalse(ShiftJis.isShiftJIS1stByte(bval));
+ }
+
+ byte[] array;
+ try{
+ // 全角スペース
+ array = "\u3000".getBytes("Shift_JIS");
+ assertTrue(ShiftJis.isShiftJIS1stByte(array[0]));
+ // 「熙」
+ array = "\u7199".getBytes("Shift_JIS");
+ assertTrue(ShiftJis.isShiftJIS1stByte(array[0]));
+ // 「"」
+ array = "\uff02".getBytes("Windows-31J");
+ assertTrue(ShiftJis.isShiftJIS1stByte(array[0]));
+ }catch(UnsupportedEncodingException e){
+ fail();
+ }
+
+ return;
+ }
+
+ /**
+ * Test of isShiftJIS2ndByte method, of class ShiftJis.
+ */
+ @Test
+ public void testIsShiftJIS2ndByte(){
+ System.out.println("isShiftJIS2ndByte");
+
+ for(int ival=0x00; ival <= 0x3f; ival++){
+ byte bval = (byte)ival;
+ assertFalse(ShiftJis.isShiftJIS2ndByte(bval));
+ }
+
+ for(int ival=0x40; ival <= 0x7e; ival++){
+ byte bval = (byte)ival;
+ assertTrue(ShiftJis.isShiftJIS2ndByte(bval));
+ }
+
+ for(int ival=0x7f; ival <= 0x7f; ival++){
+ byte bval = (byte)ival;
+ assertFalse(ShiftJis.isShiftJIS2ndByte(bval));
+ }
+
+ for(int ival=0x80; ival <= 0xfc; ival++){
+ byte bval = (byte)ival;
+ assertTrue(ShiftJis.isShiftJIS2ndByte(bval));
+ }
+
+ for(int ival=0xfd; ival <= 0xff; ival++){
+ byte bval = (byte)ival;
+ assertFalse(ShiftJis.isShiftJIS2ndByte(bval));
+ }
+
+ byte[] array;
+ try{
+ // 全角スペース
+ array = "\u3000".getBytes("Shift_JIS");
+ assertTrue(ShiftJis.isShiftJIS2ndByte(array[1]));
+ // 「熙」
+ array = "\u7199".getBytes("Shift_JIS");
+ assertTrue(ShiftJis.isShiftJIS2ndByte(array[1]));
+ // 「"」
+ array = "\uff02".getBytes("Windows-31J");
+ assertTrue(ShiftJis.isShiftJIS2ndByte(array[1]));
+ }catch(UnsupportedEncodingException e){
+ fail();
+ }
+
+ return;
+ }
+
+ /**
+ * Test of isShiftJIS method, of class ShiftJis.
+ */
+ @Test
+ public void testIsShiftJIS(){
+ System.out.println("isShiftJIS");
+
+ byte[] array;
+ try{
+ // 全角スペース
+ array = "\u3000".getBytes("Shift_JIS");
+ assertTrue(ShiftJis.isShiftJIS(array[0], array[1]));
+ // 「熙」
+ array = "\u7199".getBytes("Shift_JIS");
+ assertTrue(ShiftJis.isShiftJIS(array[0], array[1]));
+ // 「"」
+ array = "\uff02".getBytes("Windows-31J");
+ assertTrue(ShiftJis.isShiftJIS(array[0], array[1]));
+ }catch(UnsupportedEncodingException e){
+ fail();
+ }
+
+ return;
+ }
+
+}
-/*\r
- * sample handler\r
- * \r
- * License : The MIT License\r
- * Copyright(c) 2009 olyutorskii\r
- */\r
-\r
-package sample;\r
-\r
-import jp.sourceforge.jindolf.parser.DecodedContent;\r
-import jp.sourceforge.jindolf.parser.EntityConverter;\r
-import jp.sourceforge.jindolf.parser.HtmlAdapter;\r
-import jp.sourceforge.jindolf.parser.HtmlParseException;\r
-import jp.sourceforge.jindolf.parser.SeqRange;\r
-\r
-/**\r
- * サンプルのハンドラ\r
- */\r
-public class SampleHandler extends HtmlAdapter{\r
-\r
- private final EntityConverter converter = new EntityConverter();\r
-\r
- public SampleHandler(){\r
- super();\r
- return;\r
- }\r
-\r
- @Override\r
- public void talkText(DecodedContent content, SeqRange textRange)\r
- throws HtmlParseException{\r
- System.out.println(this.converter.convert(content, textRange));\r
- return;\r
- }\r
-\r
-}\r
+/*
+ * sample handler
+ *
+ * License : The MIT License
+ * Copyright(c) 2009 olyutorskii
+ */
+
+package sample;
+
+import jp.sourceforge.jindolf.parser.DecodedContent;
+import jp.sourceforge.jindolf.parser.EntityConverter;
+import jp.sourceforge.jindolf.parser.HtmlAdapter;
+import jp.sourceforge.jindolf.parser.HtmlParseException;
+import jp.sourceforge.jindolf.parser.SeqRange;
+
+/**
+ * サンプルのハンドラ
+ */
+public class SampleHandler extends HtmlAdapter{
+
+ private final EntityConverter converter = new EntityConverter();
+
+ public SampleHandler(){
+ super();
+ return;
+ }
+
+ @Override
+ public void talkText(DecodedContent content, SeqRange textRange)
+ throws HtmlParseException{
+ System.out.println(this.converter.convert(content, textRange));
+ return;
+ }
+
+}
-/*\r
- * sample parser\r
- *\r
- * License : The MIT License\r
- * Copyright(c) 2009 olyutorskii\r
- */\r
-\r
-package sample;\r
-\r
-import java.io.FileInputStream;\r
-import jp.sourceforge.jindolf.parser.*;\r
-import java.io.IOException;\r
-import java.io.InputStream;\r
-import java.nio.charset.Charset;\r
-import java.nio.charset.CharsetDecoder;\r
-import java.util.Collections;\r
-import java.util.Enumeration;\r
-import java.util.SortedMap;\r
-import java.util.TreeMap;\r
-import java.util.zip.ZipEntry;\r
-import java.util.zip.ZipFile;\r
-\r
-/**\r
- * サンプルのパーサ\r
- */\r
-public class SampleParser{\r
-\r
- private static final CharsetDecoder ud;\r
-\r
- static{\r
- ud = Charset.forName("UTF-8").newDecoder();\r
- }\r
-\r
- private SampleParser(){\r
- super();\r
- return;\r
- }\r
-\r
- public static SortedMap<String, ZipEntry> createEntryMap(ZipFile file){\r
- TreeMap<String, ZipEntry> result = new TreeMap<String, ZipEntry>();\r
-\r
- Enumeration<? extends ZipEntry> list = file.entries();\r
- while(list.hasMoreElements()){\r
- ZipEntry entry = list.nextElement();\r
- String name = entry.getName();\r
- result.put(name, entry);\r
- }\r
-\r
- return Collections.unmodifiableSortedMap(result);\r
- }\r
-\r
- public static DecodedContent contentFromStream(InputStream istream)\r
- throws IOException, DecodeException{\r
- StreamDecoder decoder = new StreamDecoder(ud);\r
- ContentBuilderUCS2 builder = new ContentBuilderUCS2();\r
-\r
- decoder.setDecodeHandler(builder);\r
-\r
- decoder.decode(istream);\r
-\r
- DecodedContent content = builder.getContent();\r
-\r
- return content;\r
- }\r
-\r
- public static void parseContent(DecodedContent content)\r
- throws HtmlParseException{\r
- HtmlParser parser = new HtmlParser();\r
- HtmlHandler handler = new SampleHandler();\r
-\r
- parser.setBasicHandler (handler);\r
- parser.setTalkHandler (handler);\r
- parser.setSysEventHandler(handler);\r
-\r
- parser.parseAutomatic(content);\r
-\r
- return;\r
- }\r
-\r
- public static void parseStream(InputStream istream)\r
- throws IOException,\r
- DecodeException,\r
- HtmlParseException{\r
- DecodedContent content = contentFromStream(istream);\r
-\r
- parseContent(content);\r
-\r
- return;\r
- }\r
-\r
- public static void main(String[] args)\r
- throws IOException,\r
- DecodeException,\r
- HtmlParseException {\r
- if(args.length == 0){\r
- System.out.println(\r
- "標準入力から人狼BBSのXHTML文書の読み取りを"\r
- +"開始します...");\r
-\r
- parseStream(System.in);\r
-\r
- System.exit(0);\r
-\r
- return;\r
- }else if(args[0].endsWith(".zip")){\r
- System.out.println(\r
- "ZIPアーカイブ内の*.htmlファイルから"\r
- +"人狼BBSのXHTML文書の読み取りを開始します...");\r
-\r
- ZipFile zipfile = new ZipFile(args[0]);\r
-\r
- SortedMap<String, ZipEntry> map = createEntryMap(zipfile);\r
-\r
- for(ZipEntry entry : map.values()){\r
- String name = entry.getName();\r
- if( ! name.endsWith(".html") ) continue;\r
-\r
- System.out.println(name + "のパースを開始...");\r
-\r
- InputStream istream = zipfile.getInputStream(entry);\r
- parseStream(istream);\r
-\r
- istream.close();\r
- }\r
-\r
- zipfile.close();\r
-\r
- System.exit(0);\r
-\r
- return;\r
- }else{\r
- System.out.println(args[0] + "のパースを開始...");\r
-\r
- InputStream istream = new FileInputStream(args[0]);\r
- parseStream(istream);\r
- istream.close();\r
-\r
- System.exit(0);\r
- }\r
-\r
- return;\r
- }\r
-\r
-}\r
+/*
+ * sample parser
+ *
+ * License : The MIT License
+ * Copyright(c) 2009 olyutorskii
+ */
+
+package sample;
+
+import java.io.FileInputStream;
+import jp.sourceforge.jindolf.parser.*;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.charset.Charset;
+import java.nio.charset.CharsetDecoder;
+import java.util.Collections;
+import java.util.Enumeration;
+import java.util.SortedMap;
+import java.util.TreeMap;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+
+/**
+ * サンプルのパーサ
+ */
+public class SampleParser{
+
+ private static final CharsetDecoder ud;
+
+ static{
+ ud = Charset.forName("UTF-8").newDecoder();
+ }
+
+ private SampleParser(){
+ super();
+ return;
+ }
+
+ public static SortedMap<String, ZipEntry> createEntryMap(ZipFile file){
+ TreeMap<String, ZipEntry> result = new TreeMap<String, ZipEntry>();
+
+ Enumeration<? extends ZipEntry> list = file.entries();
+ while(list.hasMoreElements()){
+ ZipEntry entry = list.nextElement();
+ String name = entry.getName();
+ result.put(name, entry);
+ }
+
+ return Collections.unmodifiableSortedMap(result);
+ }
+
+ public static DecodedContent contentFromStream(InputStream istream)
+ throws IOException, DecodeException{
+ StreamDecoder decoder = new StreamDecoder(ud);
+ ContentBuilderUCS2 builder = new ContentBuilderUCS2();
+
+ decoder.setDecodeHandler(builder);
+
+ decoder.decode(istream);
+
+ DecodedContent content = builder.getContent();
+
+ return content;
+ }
+
+ public static void parseContent(DecodedContent content)
+ throws HtmlParseException{
+ HtmlParser parser = new HtmlParser();
+ HtmlHandler handler = new SampleHandler();
+
+ parser.setBasicHandler (handler);
+ parser.setTalkHandler (handler);
+ parser.setSysEventHandler(handler);
+
+ parser.parseAutomatic(content);
+
+ return;
+ }
+
+ public static void parseStream(InputStream istream)
+ throws IOException,
+ DecodeException,
+ HtmlParseException{
+ DecodedContent content = contentFromStream(istream);
+
+ parseContent(content);
+
+ return;
+ }
+
+ public static void main(String[] args)
+ throws IOException,
+ DecodeException,
+ HtmlParseException {
+ if(args.length == 0){
+ System.out.println(
+ "標準入力から人狼BBSのXHTML文書の読み取りを"
+ +"開始します...");
+
+ parseStream(System.in);
+
+ System.exit(0);
+
+ return;
+ }else if(args[0].endsWith(".zip")){
+ System.out.println(
+ "ZIPアーカイブ内の*.htmlファイルから"
+ +"人狼BBSのXHTML文書の読み取りを開始します...");
+
+ ZipFile zipfile = new ZipFile(args[0]);
+
+ SortedMap<String, ZipEntry> map = createEntryMap(zipfile);
+
+ for(ZipEntry entry : map.values()){
+ String name = entry.getName();
+ if( ! name.endsWith(".html") ) continue;
+
+ System.out.println(name + "のパースを開始...");
+
+ InputStream istream = zipfile.getInputStream(entry);
+ parseStream(istream);
+
+ istream.close();
+ }
+
+ zipfile.close();
+
+ System.exit(0);
+
+ return;
+ }else{
+ System.out.println(args[0] + "のパースを開始...");
+
+ InputStream istream = new FileInputStream(args[0]);
+ parseStream(istream);
+ istream.close();
+
+ System.exit(0);
+ }
+
+ return;
+ }
+
+}