OSDN Git Service

リファクタリング. 共通メソッドのプルアップ.
[coroid/inqubus.git] / frontend / src / saccubus / net / Cookie.java
1 package saccubus.net;
2
3 import java.io.File;
4 import java.io.IOException;
5 import java.util.List;
6 import java.util.regex.Matcher;
7 import java.util.regex.Pattern;
8 import org.apache.commons.io.FileUtils;
9 import org.apache.commons.lang.StringUtils;
10
11 /**
12  *
13  * @author yuki
14  */
15 public abstract class Cookie {
16
17     private static final Pattern USER_SESSION_PATTERN = Pattern.compile("user_session_[\\d_]+");
18
19     public enum BrowserType {
20
21         NONE, MSIE, IE6, FIREFOX, CHROME,
22         OPERA, CHROMIUM, OTHER
23     }
24
25     public static Cookie create(BrowserType type) {
26         switch (type) {
27             case CHROME:
28                 return new CookieWinCrome();
29             case FIREFOX:
30                 return new CookieWinFirefox4();
31             case MSIE:
32                 return new CookieWinMsIe();
33             default:
34                 throw new UnsupportedOperationException();
35         }
36     }
37
38     public abstract String getUserSessionString() throws IOException;
39
40     /**
41      * 文字列から user_session_ で始まる文字列を切り出して返す。数字とアンダーバー以外の文字で切れる。
42      * @param str 切り出す対象文字列
43      * @return user_session 文字列。見つからなければnull。
44      */
45     protected final String cutUserSession(String str) {
46         final Matcher mather = USER_SESSION_PATTERN.matcher(str);
47         if (mather.lookingAt()) {
48             return mather.group(1);
49         }
50         return null;
51     }
52
53     /**
54      * cookieDirs ディレクトリからクッキーを見つけて user_session を返す
55      * @param cookieDirs cookie保存ディレクトリの候補.
56      * @return ユーザセッション文字列. 無ければnull.
57      */
58     protected final String getUserSessionFromDir(List<File> cookieDirs, String charsetName) throws IOException {
59         for (File dir : cookieDirs) {
60             if (dir.isDirectory()) {
61                 File[] files = dir.listFiles();
62                 for (File cookieFile : files) {
63                     if (cookieFile.isFile()) {
64                         final String cookie = FileUtils.readFileToString(cookieFile, charsetName);
65                         final String userSession = cutUserSession(cookie);
66                         if (StringUtils.isNotEmpty(userSession)) {
67                             return userSession;
68                         }
69                     }
70                 }
71             }
72         }
73
74         return null;
75     }
76 }