1 34 package net.myvietnam.mvncore.filter; 35 36 import javax.servlet.http.HttpServletRequest ; 37 38 import net.myvietnam.mvncore.MVNCoreConfig; 39 import net.myvietnam.mvncore.util.StringUtil; 40 import org.apache.commons.logging.Log; 41 import org.apache.commons.logging.LogFactory; 42 import org.apache.regexp.RE; 43 44 public final class IPFilter { 45 46 private static Log log = LogFactory.getLog(IPFilter.class); 47 48 private static RE[] blockedIPs = null; 49 50 private IPFilter() { } 52 53 static { 54 57 String [] blockedIPArray = StringUtil.getStringArray(MVNCoreConfig.getBlockedIPs(), ";"); 58 blockedIPs = new RE[blockedIPArray.length]; 59 for (int i = 0; i < blockedIPArray.length; i++) { 60 String currentIPRegExp = StringUtil.replace(blockedIPArray[i], '*', "(\\d{1,3})"); 61 currentIPRegExp = "^" + currentIPRegExp + "$"; 62 try { 63 log.debug("currentIPRegExp = " + currentIPRegExp); 64 blockedIPs[i] = new RE(currentIPRegExp); 65 } catch (Exception ex) { 66 log.error("Cannot parse the regular expression = " + currentIPRegExp, ex); 67 } 68 } 69 } 70 71 77 public static boolean filter(HttpServletRequest request) { 78 if (request == null) { 79 throw new NullPointerException ("Cannot accept a null request in IPFilter"); 80 } 81 String checkIP = request.getRemoteAddr(); 82 83 for (int i = 0; i < blockedIPs.length; i++) { 84 RE currentBlockedIP = blockedIPs[i]; 85 if (currentBlockedIP != null) { 86 synchronized (currentBlockedIP) { 87 if (currentBlockedIP.match(checkIP)) { 88 return false; 89 } 90 } 91 } 92 } 93 return true; 94 } 95 } 96 | Popular Tags |