01: package com.technoetic.xplanner.wiki;
02:
03: import com.technoetic.xplanner.XPlannerProperties;
04: import org.apache.log4j.Logger;
05:
06: import java.io.BufferedReader;
07: import java.io.InputStream;
08: import java.io.InputStreamReader;
09: import java.net.URL;
10: import java.util.HashSet;
11:
12: public class GenericWikiAdapter implements ExternalWikiAdapter {
13: private Logger log = Logger.getLogger(getClass());
14: private static HashSet existingTopics = new HashSet();
15: private String existingTopicUrlPattern;
16: private String newTopicUrlPattern;
17: public String newTopicPattern;
18:
19: public GenericWikiAdapter() {
20: XPlannerProperties properties = new XPlannerProperties();
21: initialize(properties);
22: }
23:
24: protected void initialize(XPlannerProperties properties) {
25: existingTopicUrlPattern = properties
26: .getProperty("twiki.wikiadapter.topic.url.existing");
27: newTopicUrlPattern = properties
28: .getProperty("twiki.wikiadapter.topic.url.new");
29: newTopicPattern = properties
30: .getProperty("twiki.wikiadapter.topic.newpattern");
31: }
32:
33: public String formatWikiWord(String wikiWord) {
34: return isTopicExisting(wikiWord) ? formatLinkToExistingTopic(wikiWord)
35: : formatLinkToCreateTopic(wikiWord);
36: }
37:
38: protected String formatLinkToCreateTopic(String wikiWord) {
39: return wikiWord + "<a href='"
40: + formatUrl(wikiWord, newTopicUrlPattern) + "'>?</a>";
41: }
42:
43: protected String formatLinkToExistingTopic(String wikiWord) {
44: return "<a href='"
45: + formatUrl(wikiWord, existingTopicUrlPattern) + "'>"
46: + wikiWord + "</a>";
47: }
48:
49: protected String formatUrl(String wikiWord, String urlPattern) {
50: return substituteWikiWord(wikiWord, urlPattern);
51: }
52:
53: private String substituteWikiWord(String wikiWord, String text) {
54: return text.replaceAll("\\$\\{word\\}", wikiWord);
55: }
56:
57: private boolean isTopicExisting(String wikiWord) {
58: // This is a somewhat inefficient, but general approach
59: if (existingTopics.contains(wikiWord)) {
60: return true;
61: }
62: try {
63: URL url = new URL(formatUrl(wikiWord,
64: existingTopicUrlPattern));
65: InputStream page = url.openStream();
66: BufferedReader reader = new BufferedReader(
67: new InputStreamReader(page));
68: try {
69: String line = reader.readLine();
70: while (line != null) {
71: if (line.matches(substituteWikiWord(wikiWord,
72: newTopicPattern))) {
73: return false;
74: }
75: line = reader.readLine();
76: }
77: } finally {
78: reader.close();
79: }
80: } catch (java.io.IOException e) {
81: // ignored - return false
82: return false;
83: }
84: existingTopics.add(wikiWord);
85: return true;
86: }
87:
88: public String getExistingTopicUrlPattern() {
89: return existingTopicUrlPattern;
90: }
91:
92: public String getNewTopicUrlPattern() {
93: return newTopicUrlPattern;
94: }
95:
96: public String getNewTopicPattern() {
97: return newTopicPattern;
98: }
99: }
|