/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

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