View Javadoc

1   /*
2    * Copyright 2004-2006 the Seasar Foundation and the Others.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 
13   * either express or implied. See the License for the specific language
14   * governing permissions and limitations under the License.
15   */
16  package org.seasar.tuigwaa.cms.core.wiki.base;
17  
18  import java.net.MalformedURLException;
19  import java.net.URL;
20  import java.util.ArrayList;
21  import java.util.List;
22  import java.util.regex.Matcher;
23  import java.util.regex.Pattern;
24  
25  import javax.imageio.ImageIO;
26  
27  import org.seasar.tuigwaa.cms.core.CmsConstants;
28  
29  import com.isenshi.util.PathUtils;
30  
31  /***
32   * @author someda
33   * 
34   * WikiHelper class This provides utility method for wiki parser and other wiki
35   * related object. Basically, it does not provide node related tasks for
36   * WikiParser but provide only static method which is useful during parsing
37   * phase. Also this might be useful for plugin execution phase.
38   */
39  public class WikiHelper {
40  
41  	public static final int LIST_TYPE_NORMAL = 1;
42  
43  	public static final int LIST_TYPE_NUMERICAL = 2;
44  
45  	public static final int TABLE_TYPE_HEADER = 1;
46  
47  	public static final int TABLE_TYPE_FOOTER = 2;
48  
49  	public static final String ANCHOR_MARK = "#";
50  
51  	public static final String LINK_DELIMITER = ":";
52  
53  	public static final String ALIAS_DELIMITER = ">";
54  
55  	private static final Pattern NEWLINE = Pattern.compile("\n");
56  
57  	private static final Pattern ANCHOR = Pattern
58  			.compile(".*//[#[a-zA-Z][0-9a-zA-Z]+//]$");
59  
60  	private static final Pattern CR = Pattern.compile("\r");
61  
62  	public static final String ANCHOR_PREFIX = "[#tg";
63  
64  	public static final String ANCHOR_SUFFIX = "]";
65  
66  	// private static final String[] IMAGE_SUFFIX =
67  	// {".jpg",".jpeg",".gif",".bmp",".png"};
68  	private static final String[] IMAGE_SUFFIX = ImageIO.getReaderFormatNames();
69  
70  	// private static final String ARGS_DELIMITER = ",";
71  
72  	
73  	
74  	private static final String VTL_ARGS = "(//([//////$//w//s//[//],;//&]+//))?";
75  	
76  	private static final Pattern VTL_CMD = Pattern
77  			.compile("(<br ///>#|^#|\n#|\r#)([a-z]*" + VTL_ARGS + ")($|<br ///>?)");
78  
79  	public static boolean isEmail(String image) {
80  		return (image.indexOf("@") != -1);
81  	}
82  
83  	public static int getListType(String image) {
84  		int type = 0;
85  		if (image.equals("-") || image.equals("--") || image.equals("---")) {
86  			type = LIST_TYPE_NORMAL;
87  		} else if (image.equals("+") || image.equals("++")
88  				|| image.equals("+++")) {
89  			type = LIST_TYPE_NUMERICAL;
90  		}
91  		return type;
92  	}
93  
94  	public static String[] split(String image, String delimiter) {
95  		String[] s = new String[2];
96  		int idx = image.indexOf(delimiter);
97  		if (idx != -1) {
98  			s[0] = image.substring(0, idx);
99  			s[1] = image.substring(idx + 1, image.length());
100 		} else {
101 			s[0] = image;
102 			s[1] = "";
103 		}
104 		return s;
105 	}
106 
107 	public static String deleteParenthesis(String image, String left,
108 			String right) {
109 		return deleteParenthesis(image, left, right, true);
110 	}
111 
112 	public static String deleteParenthesis(String image, String left,
113 			String right, boolean isWide) {
114 		int idx = 0;
115 		int lidx = 0;
116 		int ridx = image.length();
117 
118 		if ((idx = image.indexOf(left)) != -1) {
119 			lidx = idx + 1;
120 		}
121 
122 		if (isWide) {
123 			if ((idx = image.lastIndexOf(right)) != -1) {
124 				ridx = idx;
125 			}
126 		} else {
127 			if ((idx = image.indexOf(right)) != -1) {
128 				ridx = idx;
129 			}
130 		}
131 		return (ridx > lidx) ? image.substring(lidx, ridx) : "";
132 	}
133 
134 	public static String beforeSavePage(String contentType, String content) {
135 		if (CmsConstants.CONTENTTYPE_XWIKI.equals(contentType)) {
136 			return setAnchorToHeading(content);
137 		} else if (CmsConstants.CONTENTTYPE_HTML.equals(contentType)) {
138 			return removeCarriageReturn(content);
139 		} else if(CmsConstants.CONTENTTYPE_DFORM.equals(contentType)){
140 			//return toVTL(content);
141 			return toJSP(content);
142 		}
143 		return content;
144 	}
145 
146 	/***
147 	 * generate anchor data from object hashcode
148 	 * 
149 	 * @param contents
150 	 *            wiki contents
151 	 * @return contents with anchor data
152 	 */
153 	public static String setAnchorToHeading(String contents) {
154 		String mod = removeCarriageReturn(contents);
155 		String[] s = NEWLINE.split(mod);
156 
157 		StringBuffer buf = new StringBuffer();
158 		int hashcode = contents.hashCode();
159 		for (int i = 0; i < s.length; i++) {
160 			buf.append(s[i]);
161 
162 			Matcher m = ANCHOR.matcher(s[i]);
163 			if (s[i].indexOf("*") == 0 && !m.matches()) {
164 				buf.append(ANCHOR_PREFIX + Integer.toHexString(hashcode)
165 						+ ANCHOR_SUFFIX);
166 				hashcode++;
167 			}
168 			buf.append(CmsConstants.LINEBREAK_CODE);
169 		}
170 		return buf.toString();
171 	}
172 
173 	/***
174 	 * remove carriage return
175 	 * 
176 	 * @param contents
177 	 *            html contents
178 	 */
179 	public static String removeCarriageReturn(String contents) {
180 		Matcher crm = CR.matcher(contents);
181 		return crm.replaceAll("");
182 	}
183 
184 	/***
185 	 * Discriminates the specifid string represents image file or not. This see
186 	 * the string as image if it ends with <strong>.jpg,.jpeg,.gif,.png,and .bmp</strong>
187 	 * in a case insensitive mannger.
188 	 */
189 	public static boolean isImage(String s) {
190 
191 		boolean flag = false;
192 		String extension = PathUtils.getExtension(s);
193 
194 		if (extension != null && !extension.equals("")) {
195 			for (int i = 0; i < IMAGE_SUFFIX.length; i++) {
196 				if (extension.equalsIgnoreCase(IMAGE_SUFFIX[i])) {
197 					flag = true;
198 					break;
199 				}
200 			}
201 		}
202 		return flag;
203 	}
204 
205 	private static final String JSP_HEADER = "<%@ page contentType=\"text/html; charset=Windows-31J\" %>\n" +  
206 	"<%@ taglib uri=\"/WEB-INF/tgw-c.tld\" prefix=\"tgwc\" %>\n";
207 
208 	public static String toJSP(String str) {
209 		return JSP_HEADER + str;
210 	}
211 
212 	public static String toVTL(String str) {
213 		str = str.replaceAll("//$", "//////$");
214 		Matcher matcher = VTL_CMD.matcher(str);
215 		StringBuffer buf = new StringBuffer();
216 		while (matcher.find()) {
217 			String vtlcmd = matcher.group(2);
218 			vtlcmd = vtlcmd.replaceAll("//&quot;", "\"");
219 			matcher.appendReplacement(buf, "\n#" + vtlcmd + "\n");
220 		}
221 		matcher.appendTail(buf);
222 		str = buf.toString();
223 		str = str.replaceAll("//////$", "//$");
224 		return str;
225 	}
226 
227 
228 	/***
229 	 * Discriminates the specifid string represents URL or not.
230 	 */
231 	public static boolean isURL(String s) {
232 
233 		try {
234 			new URL(s);
235 			return true;
236 		} catch (MalformedURLException e) {
237 			// do nothing
238 		}
239 		return false;
240 	}
241 
242 	public static String[] splitArgs(String image) {
243 		String s = deleteParenthesis(image, "(", ")");
244 
245 		StringBuffer buf = new StringBuffer();
246 		List argsList = new ArrayList();
247 		int cnt = 0;
248 		int parenthesis = 0;
249 		for (int i = 0; i < s.length(); i++) {
250 			char c = s.charAt(i);
251 			if (c == '&') { // enter plugin mode
252 				cnt++;
253 			}
254 
255 			if (cnt > 0 && (c == '(' || c == '{')) { // enter parenthesis
256 				// mode
257 				parenthesis++;
258 			}
259 
260 			if (cnt > 0 && (c == ')' || c == '}')) {
261 				parenthesis--;
262 			}
263 
264 			// if(c == ';'){
265 			// cnt--;
266 			// }
267 
268 			if (c == ',') {
269 				if ((cnt > 0 && parenthesis == 0) || cnt == 0) {
270 					argsList.add(buf.toString().trim());
271 					buf = new StringBuffer();
272 					cnt = 0;
273 					continue;
274 				}
275 			}
276 			buf.append(c);
277 		}
278 
279 		if (buf.length() > 0) {
280 			argsList.add(buf.toString().trim());
281 		}
282 		return (String[]) argsList.toArray(new String[argsList.size()]);
283 	}
284 
285 	public static int getTableType(String image) {
286 		int type = 0;
287 		if ("h".equals(image) || "H".equals(image)) {
288 			type = TABLE_TYPE_HEADER;
289 		} else if ("f".equals(image) || "F".equals(image)) {
290 			type = TABLE_TYPE_FOOTER;
291 		}
292 		return type;
293 	}
294 
295 }