1 11 12 package org.jivesoftware.messenger.plugin; 13 14 import org.xmpp.packet.Message; 15 16 import java.util.ArrayList ; 17 import java.util.Collection ; 18 import java.util.regex.Matcher ; 19 import java.util.regex.Pattern ; 20 21 27 public class ContentFilter { 28 29 private String patterns; 30 31 private Collection <Pattern > compiledPatterns = new ArrayList <Pattern >(); 32 33 private String mask; 34 35 36 42 public ContentFilter() { 43 } 44 45 50 public void setPatterns(String patterns) { 51 if (patterns != null) { 52 this.patterns = patterns; 53 String [] data = patterns.split(","); 54 55 compiledPatterns.clear(); 56 57 for (int i = 0; i < data.length; i++) { 58 compiledPatterns.add(Pattern.compile(data[i])); 59 } 60 } 61 else { 62 clearPatterns(); 63 } 64 65 } 66 67 public String getPatterns() { 68 return this.patterns; 69 } 70 71 75 public void clearPatterns() { 76 patterns = null; 77 compiledPatterns.clear(); 78 } 79 80 85 public void setMask(String mask) { 86 this.mask = mask; 87 } 88 89 92 public String getMask() { 93 return mask; 94 } 95 96 101 public void clearMask() { 102 mask = null; 103 } 104 105 106 109 public boolean isMaskingContent() { 110 return mask != null; 111 } 112 113 120 public boolean filter(Message msg) { 121 boolean hasMatch = false; 122 123 if (msg.getSubject() != null) { 124 if (hasMatch(msg.getSubject())) { 125 hasMatch = true; 126 if (isMaskingContent()) { 127 String newSubject = replaceContent(msg.getSubject()); 128 msg.setSubject(newSubject); 129 } 130 } 131 } 132 133 if (msg.getBody() != null) { 134 if (hasMatch(msg.getBody())) { 135 hasMatch = true; 136 if (isMaskingContent()) { 137 String newBody = replaceContent(msg.getBody()); 138 msg.setBody(newBody); 139 } 140 } 141 } 142 143 return hasMatch; 144 } 145 146 private String replaceContent(String content) { 147 for (Pattern pattern : compiledPatterns) { 148 Matcher m = pattern.matcher(content); 149 content = m.replaceAll(mask); 150 } 151 152 return content; 153 } 154 155 161 private boolean hasMatch(String content) { 162 boolean hasMatch = false; 163 164 for (Pattern pattern : compiledPatterns) { 165 Matcher m = pattern.matcher(content); 166 167 if (m.find()) { 168 hasMatch = true; 169 break; 170 } 171 } 172 173 return hasMatch; 174 } 175 } | Popular Tags |