OSDN Git Service

a0ac37a5ec85d29d6ba1c103a6f1d813155c0a46
[coroid/NicoBrowser.git] / src / nicobrowser / NamePattern.java
1 package nicobrowser;
2
3 /**
4  *
5  * @author yuki
6  */
7 public class NamePattern {
8
9     private static final String titlePattern = "{title}";
10     private static final String idPattern = "{id}";
11     private static final String lowPattern = "{low}";
12     private final String pattern;
13     private String replaceFrom = "";
14     private String replaceTo = "";
15     private String id = "";
16     private String title = "";
17     private boolean isNotLow = true;
18
19     public NamePattern(String pattern) {
20         this.pattern = pattern;
21     }
22
23     /**
24      * 保存ファイル名の命名規則.
25      * @param pattern 命名パターン.
26      * @param replaceFrom 禁則文字を指定する.
27      * @param replaceTo 禁則文字をこの文字列に置換する.
28      * @param title ファイル名に用いるタイトル文字列.
29      */
30     public NamePattern(String pattern, String replaceFrom, String replaceTo, String title) {
31         this.pattern = pattern;
32         this.replaceFrom = replaceFrom;
33         this.replaceTo = replaceTo;
34         this.title = title;
35     }
36
37     public final String createFileName() {
38         String res = replacePlaceHolder(pattern);
39         return replaceIllegalChar(res);
40     }
41
42     public final String createFileName(String id, boolean isNotLow) {
43         this.id = id;
44         this.isNotLow = isNotLow;
45
46         return createFileName();
47     }
48
49     public final void setId(String id) {
50         this.id = id;
51     }
52
53     public final void setIsNotLow(boolean isNotLow) {
54         this.isNotLow = isNotLow;
55     }
56
57     public final void setReplaceFrom(String replaceFrom) {
58         this.replaceFrom = replaceFrom;
59     }
60
61     public final void setReplaceTo(String replaceTo) {
62         this.replaceTo = replaceTo;
63     }
64
65     public final void setTitle(String title) {
66         this.title = title;
67     }
68
69     protected String replacePlaceHolder(String str) {
70         String res = str.replace(titlePattern, title);
71         res = res.replace(idPattern, id);
72         String low = isNotLow ? "" : "low";
73         res = res.replace(lowPattern, low);
74         return res;
75     }
76
77     private String replaceIllegalChar(String res) {
78         // TODO 正規表現で書き直す
79         char[] replaceds = new char[replaceFrom.length()];
80         replaceFrom.getChars(0, replaceFrom.length(), replaceds, 0);
81         StringBuilder str = new StringBuilder();
82         for (int i = 0; i < res.length(); i++) {
83             char c = res.charAt(i);
84             String moji = String.valueOf(c);
85             for (char replaced : replaceds) {
86                 if (c == replaced) {
87                     moji = replaceTo;
88                 }
89             }
90             str.append(moji);
91         }
92         return str.toString();
93     }
94 }