View Javadoc

1   package org.portletbridge.portlet;
2   
3   import java.util.regex.Matcher;
4   import java.util.regex.Pattern;
5   
6   public class RegexContentRewriter implements ContentRewriter {
7   
8       private Pattern urlPattern;
9   
10      public RegexContentRewriter(String pattern) {
11          urlPattern = Pattern
12                  .compile(pattern);
13      }
14      
15      public String rewrite(String baseUrl, String content, LinkRewriter linkRewriter) {
16          Matcher matcher = urlPattern.matcher(content);
17          StringBuffer sb = new StringBuffer();
18          while(matcher.find()) {
19              int group = extractGroup(matcher);
20              if(group > 0) {
21                  String before = content.substring(matcher.start(), matcher.start(group));
22                  String url = matcher.group(group);
23                  String after = content.substring(matcher.end(group), matcher.end());
24                  matcher.appendReplacement(sb, before + linkRewriter.link(baseUrl, url) + after);
25              }
26          }
27          matcher.appendTail(sb);
28          return sb.toString();
29      }
30  
31      private int extractGroup(Matcher matcher) {
32          int matchingGroup = -1;
33          for(int i = 1; i <= matcher.groupCount(); i++) {
34              if(matcher.start(i) > -1) {
35                  matchingGroup = i;
36                  break;
37              }
38          }
39          return matchingGroup;
40      }
41  
42  }