1 package club.wpia.gigi.util;
3 import java.util.HashMap;
4 import java.util.TreeSet;
6 import club.wpia.gigi.GigiApiException;
8 public class RateLimit {
10 public static final class RateLimitException extends GigiApiException {
12 private static final long serialVersionUID = 1L;
14 public RateLimitException() {
15 super("Rate limit exceeded.");
19 private class Entry implements Comparable<Entry> {
27 public Entry(long firstAccess, String feature) {
28 this.firstAccess = firstAccess;
29 this.feature = feature;
32 public void access() {
37 public int compareTo(Entry o) {
38 return feature.compareTo(o.feature);
41 public boolean isExpired() {
42 return firstAccess + time < System.currentTimeMillis();
47 private final int maxcount;
49 private final long time;
51 TreeSet<Entry> set = new TreeSet<Entry>();
53 HashMap<String, Entry> feat = new HashMap<>();
55 public RateLimit(int maxcount, long time) {
56 this.maxcount = maxcount;
60 public synchronized boolean isLimitExceeded(String feature) {
62 Entry e = feat.get(feature);
64 e = new Entry(System.currentTimeMillis(), feature);
70 return e.count > maxcount;
73 private void clean() {
74 while (set.size() > 0) {
78 feat.remove(e.feature);
85 public synchronized void bypass() {