~james-page/ubuntu/oneiric/jenkins-winstone/827651

« back to all changes in this revision

Viewing changes to src/java/winstone/URIUtil.java

  • Committer: Bazaar Package Importer
  • Author(s): James Page
  • Date: 2011-06-29 12:16:17 UTC
  • Revision ID: james.westby@ubuntu.com-20110629121617-vd3ha6lp4nqvxkbr
Tags: upstream-0.9.10-jenkins-25+dfsg
ImportĀ upstreamĀ versionĀ 0.9.10-jenkins-25+dfsg

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
package winstone;
 
2
 
 
3
import java.util.ArrayList;
 
4
import java.util.Arrays;
 
5
import java.util.Iterator;
 
6
import java.util.List;
 
7
 
 
8
/**
 
9
 * @author Kohsuke Kawaguchi
 
10
 */
 
11
public class URIUtil {
 
12
    /**
 
13
     * Eliminates "." and ".." in the path.
 
14
     * So that this method can be used for any string that looks like an URI,
 
15
     * this method preserves the leading and trailing '/'.
 
16
     */
 
17
    static String canonicalPath(String path) {
 
18
        List r = new ArrayList(Arrays.asList(path.split("/+")));
 
19
        for (int i=0; i<r.size(); ) {
 
20
            String cur = (String)r.get(i);
 
21
            if (cur.length()==0 || cur.equals(".")) {
 
22
                // empty token occurs for example, "".split("/+") is [""]
 
23
                r.remove(i);
 
24
            } else
 
25
            if (cur.equals("..")) {
 
26
                // i==0 means this is a broken URI.
 
27
                r.remove(i);
 
28
                if (i>0) {
 
29
                    r.remove(i-1);
 
30
                    i--;
 
31
                }
 
32
            } else {
 
33
                i++;
 
34
            }
 
35
        }
 
36
 
 
37
        StringBuilder buf = new StringBuilder();
 
38
        if (path.startsWith("/"))
 
39
            buf.append('/');
 
40
        boolean first = true;
 
41
        for (Iterator itr = r.iterator(); itr.hasNext();) {
 
42
            String token = (String) itr.next();
 
43
            if (!first)     buf.append('/');
 
44
            else            first = false;
 
45
            buf.append(token);
 
46
        }
 
47
        // translation: if (path.endsWith("/") && !buf.endsWith("/"))
 
48
        if (path.endsWith("/") && (buf.length()==0 || buf.charAt(buf.length()-1)!='/'))
 
49
            buf.append('/');
 
50
        return buf.toString();
 
51
    }
 
52
 
 
53
}