OSDN Git Service

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