1 package org.cacert.gigi.util;
3 import java.util.HashMap;
4 import java.util.TreeSet;
6 import org.cacert.gigi.GigiApiException;
8 public class RateLimit {
10 public static final class RateLimitException extends GigiApiException {
12 public RateLimitException() {
13 super("Rate limit exceeded.");
17 private class Entry implements Comparable<Entry> {
25 public Entry(long firstAccess, String feature) {
26 this.firstAccess = firstAccess;
27 this.feature = feature;
30 public void access() {
35 public int compareTo(Entry o) {
36 return feature.compareTo(o.feature);
39 public boolean isExpired() {
40 return firstAccess + time < System.currentTimeMillis();
45 private final int maxcount;
47 private final long time;
49 TreeSet<Entry> set = new TreeSet<Entry>();
51 HashMap<String, Entry> feat = new HashMap<>();
53 public RateLimit(int maxcount, long time) {
54 this.maxcount = maxcount;
58 public synchronized boolean isLimitExceeded(String feature) {
60 Entry e = feat.get(feature);
62 e = new Entry(System.currentTimeMillis(), feature);
68 return e.count > maxcount;
71 private void clean() {
72 while (set.size() > 0) {
76 feat.remove(e.feature);
83 public synchronized void bypass() {