PageRenderTime 26ms CodeModel.GetById 12ms app.highlight 9ms RepoModel.GetById 2ms app.codeStats 0ms

/hudson-core/src/main/java/hudson/console/UrlAnnotator.java

http://github.com/hudson/hudson
Java | 48 lines | 30 code | 7 blank | 11 comment | 2 complexity | c4a6008b6c6145d73cd8a47ae01bf0cb MD5 | raw file
 1package hudson.console;
 2
 3import hudson.Extension;
 4import hudson.MarkupText;
 5import hudson.MarkupText.SubText;
 6
 7import java.util.regex.Pattern;
 8
 9/**
10 * Annotates URLs in the console output to hyperlink.
11 *
12 * @author Kohsuke Kawaguchi
13 */
14@Extension
15public class UrlAnnotator extends ConsoleAnnotatorFactory<Object> {
16    @Override
17    public ConsoleAnnotator newInstance(Object context) {
18        return new UrlConsoleAnnotator();
19    }
20
21    private static class UrlConsoleAnnotator extends ConsoleAnnotator {
22        public ConsoleAnnotator annotate(Object context, MarkupText text) {
23            for (SubText t : text.findTokens(URL)) {
24                int prev = t.start() - 1;
25                char ch = prev>=0 ? text.charAt(prev) : ' ';
26                int idx = OPEN.indexOf(ch);
27                if (idx>=0) {// if inside a bracket, exclude the end bracket.
28                    t=t.subText(0,t.getText().indexOf(CLOSE.charAt(idx)));
29                }
30                t.href(t.getText());
31            }
32            return this;
33        }
34
35        private static final long serialVersionUID = 1L;
36
37        /**
38         * Starts with a word boundary and protocol identifier,
39         * don't include any whitespace, '&lt;', nor '>'.
40         * In addition, the last character shouldn't be ',' ':', '"', etc, as often those things show up right next
41         * to URL in plain text (e.g., test="http://www.example.com/")
42         */
43        private static final Pattern URL = Pattern.compile("\\b(http|https|ftp)://[^\\s<>]+[^\\s<>,:\"'()\\[\\]=]");
44
45        private static final String OPEN = "'\"()[]<>";
46        private static final String CLOSE= "'\")(][><";
47    }
48}