1 17 18 package org.apache.roller.util; 19 20 import java.util.HashMap ; 21 import java.util.Map ; 22 import org.apache.commons.logging.Log; 23 import org.apache.commons.logging.LogFactory; 24 import org.apache.roller.util.cache.Cache; 25 import org.apache.roller.util.cache.CacheManager; 26 import org.apache.roller.util.cache.ExpiringCacheEntry; 27 28 29 36 public class GenericThrottle { 37 38 private static Log log = LogFactory.getLog(GenericThrottle.class); 39 40 private int threshold = 1; 42 private int interval = 0; 43 44 Cache clientHistoryCache = null; 46 47 48 public GenericThrottle(int thresh, int inter, int maxEntries) { 49 50 if(thresh > -1) { 52 this.threshold = thresh; 53 } 54 55 if(inter > 0) { 57 this.interval = inter; 58 } 59 60 if(maxEntries < 0) { 62 maxEntries = 1; 63 } 64 65 Map cacheProps = new HashMap (); 67 cacheProps.put("id", "throttle"); 68 cacheProps.put("size", ""+maxEntries); 69 cacheProps.put("timeout", ""+this.interval); 70 71 this.clientHistoryCache = CacheManager.constructCache(null, cacheProps); 73 } 74 75 76 85 public boolean processHit(String clientId) { 86 87 if(clientId == null) { 88 return false; 89 } 90 91 ClientInfo client = null; 93 ExpiringCacheEntry cacheEntry = (ExpiringCacheEntry) this.clientHistoryCache.get(clientId); 94 if(cacheEntry != null) { 95 log.debug("HIT "+clientId); 96 client = (ClientInfo) cacheEntry.getValue(); 97 98 if(client == null) { 100 log.debug("EXPIRED "+clientId); 101 this.clientHistoryCache.remove(clientId); 102 } 103 } 104 105 if(client != null) { 108 client.hits++; 109 110 log.debug("STATUS "+clientId+" - "+client.hits+" hits since "+client.start); 111 112 if(client.hits > this.threshold) { 114 return true; 115 } 116 117 } else { 118 log.debug("NEW "+clientId); 119 120 ClientInfo newClient = new ClientInfo(); 122 newClient.hits = 1; 123 newClient.id = clientId; 124 125 ExpiringCacheEntry newEntry = new ExpiringCacheEntry(newClient, this.interval); 126 this.clientHistoryCache.put(clientId, newEntry); 127 } 128 129 return false; 130 } 131 132 133 141 public boolean isAbusive(String clientId) { 142 143 if(clientId == null) { 144 return false; 145 } 146 147 ClientInfo client = null; 149 ExpiringCacheEntry cacheEntry = (ExpiringCacheEntry) this.clientHistoryCache.get(clientId); 150 if(cacheEntry != null) { 151 log.debug("HIT "+clientId); 152 client = (ClientInfo) cacheEntry.getValue(); 153 154 if(client == null) { 156 log.debug("EXPIRED "+clientId); 157 this.clientHistoryCache.remove(clientId); 158 } 159 } 160 161 if(client != null) { 162 return (client.hits > this.threshold); 163 } else { 164 return false; 165 } 166 } 167 168 169 private class ClientInfo { 171 172 public String id = null; 173 public int hits = 0; 174 public java.util.Date start = new java.util.Date (); 175 176 } 177 178 } 179 | Popular Tags |