01: /*
02:
03: This software is OSI Certified Open Source Software.
04: OSI Certified is a certification mark of the Open Source Initiative.
05:
06: The license (Mozilla version 1.0) can be read at the MMBase site.
07: See http://www.MMBase.org/license
08:
09: */
10:
11: package org.mmbase.util;
12:
13: import org.mmbase.util.logging.Logger;
14: import org.mmbase.util.logging.Logging;
15:
16: /**
17: * For an important part stolen from jakarta vfs (only one function).
18: * @javadoc
19: *
20: * @author Michiel Meeuwissen
21: * @since MMBase-1.7
22: * @version $Id: UriParser.java,v 1.3 2004/09/30 17:19:50 pierre Exp $
23: */
24: public class UriParser {
25:
26: private static final Logger log = Logging
27: .getLoggerInstance(UriParser.class);
28:
29: final static char separatorChar = java.io.File.separator.charAt(0); // '\' for windows '/' for other oses.
30:
31: /**
32: * Converts an absolute path into a relative path.
33: *
34: * @param basePath The base path.
35: * @param path The path to convert.
36: */
37: static public String makeRelative(final String basePath,
38: final String path) {
39: if (log.isDebugEnabled()) {
40: log
41: .debug("converting " + path + " relative to "
42: + basePath);
43: }
44: // Calculate the common prefix
45: final int basePathLen = basePath.length();
46: final int pathLen = path.length();
47:
48: // Deal with root
49: if (basePathLen == 1 && pathLen == 1) {
50: return ".";
51: } else if (basePathLen == 1) {
52: return path.substring(1);
53: }
54:
55: final int maxlen = Math.min(basePathLen, pathLen);
56: int pos = 0;
57: for (; pos < maxlen && basePath.charAt(pos) == path.charAt(pos); pos++) {
58: }
59:
60: if (pos == basePathLen && pos == pathLen) {
61: // Same names
62: return ".";
63: } else if (pos == basePathLen && pos < pathLen
64: && path.charAt(pos) == separatorChar) {
65: // A descendent of the base path
66: return path.substring(pos + 1);
67: }
68:
69: // Strip the common prefix off the path
70: final StringBuffer buffer = new StringBuffer();
71: if (pathLen > 1
72: && (pos < pathLen || basePath.charAt(pos) != separatorChar)) {
73: // Not a direct ancestor, need to back up
74: pos = basePath.lastIndexOf(separatorChar, pos);
75: buffer.append(path.substring(pos));
76: }
77:
78: // Prepend a '../' for each element in the base path past the common
79: // prefix
80: buffer.insert(0, "..");
81: pos = basePath.indexOf(separatorChar, pos + 1);
82: while (pos != -1) {
83: buffer.insert(0, "../");
84: pos = basePath.indexOf(separatorChar, pos + 1);
85: }
86: if (log.isDebugEnabled()) {
87: log.debug("is: " + buffer);
88: }
89:
90: return buffer.toString();
91: }
92: }
|