01: // Copyright (C) 2003,2004,2005 by Object Mentor, Inc. All rights reserved.
02: // Released under the terms of the GNU General Public License version 2 or later.
03: package fitnesse.wiki;
04:
05: import fitnesse.wikitext.widgets.WikiWordWidget;
06:
07: import java.util.Iterator;
08: import java.util.regex.Pattern;
09:
10: public class PathParser {
11: public static final String PATH_SEPARATOR = ".";
12: private static final Pattern wikiWordPattern = Pattern
13: .compile(WikiWordWidget.REGEXP);
14: private WikiPagePath path;
15:
16: public static WikiPagePath parse(String pathName) {
17: return new PathParser().makePath(pathName);
18: }
19:
20: private WikiPagePath makePath(String pathName) {
21: path = new WikiPagePath();
22: if (pathName.equals("")) {
23: return path;
24: } else if (pathName.equals("root")
25: || pathName.equals(PATH_SEPARATOR)) {
26: path.makeAbsolute();
27: return path;
28: } else {
29: return parsePathName(pathName);
30: }
31: }
32:
33: private WikiPagePath parsePathName(String pathName) {
34: if (pathName.startsWith(PATH_SEPARATOR)) {
35: path.makeAbsolute();
36: pathName = pathName.substring(1);
37: } else if (pathName.startsWith(">") || pathName.startsWith("^")) {
38: path.setPathMode(WikiPagePath.Mode.SUB_PAGE);
39: pathName = pathName.substring(1);
40: } else if (pathName.startsWith("<")) {
41: path.setPathMode(WikiPagePath.Mode.BACKWARD_SEARCH);
42: pathName = pathName.substring(1);
43: }
44: String[] names = pathName.split("\\" + PATH_SEPARATOR);
45: for (int i = 0; i < names.length; i++) {
46: String pageName = names[i];
47: if (nameIsValid(pageName))
48: path.addName(pageName);
49: else
50: return null;
51: }
52: return path;
53: }
54:
55: private static boolean nameIsValid(String name) {
56: return wikiWordPattern.matcher(name).matches();
57: }
58:
59: public static String render(WikiPagePath path) {
60: StringBuffer renderedPath = new StringBuffer();
61: if (path.isSubPagePath())
62: renderedPath.append(">");
63: else if (path.isBackwardSearchPath())
64: renderedPath.append("<");
65: else if (path.isAbsolute()) {
66: renderedPath.append(".");
67: }
68:
69: Iterator i = path.getNames().iterator();
70: if (i.hasNext()) {
71: String name = (String) i.next();
72: renderedPath.append(name);
73: }
74: while (i.hasNext()) {
75: renderedPath.append(PATH_SEPARATOR).append(i.next());
76: }
77: return renderedPath.toString();
78: }
79: }
|