File: URIUtil.java

package info (click to toggle)
jenkins-winstone 0.9.10-jenkins-37+dfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 2,292 kB
  • sloc: java: 14,196; xml: 943; makefile: 110; sh: 11
file content (78 lines) | stat: -rw-r--r-- 2,443 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package winstone;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @author Kohsuke Kawaguchi
 */
public class URIUtil {
    /**
     * Eliminates "." and ".." in the path.
     * So that this method can be used for any string that looks like an URI,
     * this method preserves the leading and trailing '/'.
     */
    static String canonicalPath(String path) {
        List<String> r = new ArrayList<String>(Arrays.asList(path.split("[/\\\\]+")));
        for (int i=0; i<r.size(); ) {
            String cur = r.get(i);
            if (cur.length()==0 || cur.equals(".")) {
                // empty token occurs for example, "".split("/+") is [""]
                r.remove(i);
            } else
            if (cur.equals("..")) {
                // i==0 means this is a broken URI.
                r.remove(i);
                if (i>0) {
                    r.remove(i-1);
                    i--;
                }
            } else {
                i++;
            }
        }

        StringBuilder buf = new StringBuilder();
        if (path.startsWith("/"))
            buf.append('/');
        boolean first = true;
        for (Object aR : r) {
            String token = (String) aR;
            if (!first) buf.append('/');
            else first = false;
            buf.append(token);
        }
        // translation: if (path.endsWith("/") && !buf.endsWith("/"))
        if (path.endsWith("/") && (buf.length()==0 || buf.charAt(buf.length()-1)!='/'))
            buf.append('/');
        return buf.toString();
    }

    /**
     * Performs necessary escaping to render arbitrary plain text as plain text without any markup.
     */
    public static String htmlEscape(String text) {
        StringBuilder buf = new StringBuilder(text.length()+64);
        for( int i=0; i<text.length(); i++ ) {
            char ch = text.charAt(i);
            if(ch=='<')
                buf.append("&lt;");
            else
            if(ch=='&')
                buf.append("&amp;");
            else
                buf.append(ch);
        }
        return buf.toString();
    }

    /**
     * Removes any occurrence of CR and LF in the text.
     */
    public static String noCRLF(String text) {
        // so long as the value doesn't contain CR nor LF, don't really care how they get replaced
        return text.replace('\r',' ').replace('\n',' ');
    }
}