X-Git-Url: https://code.wpia.club/?a=blobdiff_plain;f=src%2Forg%2Fcacert%2Fgigi%2Futil%2FRateLimit.java;fp=src%2Forg%2Fcacert%2Fgigi%2Futil%2FRateLimit.java;h=46098bf5af2e86677640a4a932c5df80c4eb8d7e;hb=a64b40f37a1845a4b9c5f1c0e962babca4b2d291;hp=0000000000000000000000000000000000000000;hpb=6b7d6a59d006d1d252ccbe86a4f5ab7099c6c002;p=gigi.git diff --git a/src/org/cacert/gigi/util/RateLimit.java b/src/org/cacert/gigi/util/RateLimit.java new file mode 100644 index 00000000..46098bf5 --- /dev/null +++ b/src/org/cacert/gigi/util/RateLimit.java @@ -0,0 +1,73 @@ +package org.cacert.gigi.util; + +import java.util.HashMap; +import java.util.TreeSet; + +public class RateLimit { + + private class Entry implements Comparable { + + long firstAccess; + + int count = 1; + + String feature; + + public Entry(long firstAccess, String feature) { + this.firstAccess = firstAccess; + this.feature = feature; + } + + public void access() { + count++; + } + + @Override + public int compareTo(Entry o) { + return feature.compareTo(o.feature); + } + + public boolean isExpired() { + return firstAccess + time < System.currentTimeMillis(); + } + + } + + private final int maxcount; + + private final long time; + + TreeSet set = new TreeSet(); + + HashMap feat = new HashMap<>(); + + public RateLimit(int maxcount, long time) { + this.maxcount = maxcount; + this.time = time; + } + + public synchronized boolean isLimitExceeded(String feature) { + clean(); + Entry e = feat.get(feature); + if (e == null) { + e = new Entry(System.currentTimeMillis(), feature); + set.add(e); + feat.put(feature, e); + } else { + e.access(); + } + return e.count > maxcount; + } + + private void clean() { + while (set.size() > 0) { + Entry e = set.last(); + if (e.isExpired()) { + set.remove(e); + feat.remove(e.feature); + } else { + return; + } + } + } +}