2019-08-09 19:28:08 +03:00
|
|
|
package pro.gravit.launchserver.components;
|
|
|
|
|
2019-08-25 09:48:26 +03:00
|
|
|
import java.util.ArrayList;
|
2019-08-09 19:28:08 +03:00
|
|
|
import java.util.HashMap;
|
2019-08-25 09:48:26 +03:00
|
|
|
import java.util.List;
|
2019-08-09 19:28:08 +03:00
|
|
|
import java.util.Map;
|
|
|
|
|
2019-08-13 14:58:56 +03:00
|
|
|
import pro.gravit.launcher.NeedGarbageCollection;
|
|
|
|
|
2019-08-25 09:48:26 +03:00
|
|
|
public abstract class AbstractLimiter<T> extends Component implements NeedGarbageCollection {
|
|
|
|
public int rateLimit;
|
|
|
|
public int rateLimitMillis;
|
|
|
|
public List<T> exclude = new ArrayList<>();
|
2019-08-09 19:28:08 +03:00
|
|
|
|
|
|
|
@Override
|
|
|
|
public void garbageCollection() {
|
|
|
|
long time = System.currentTimeMillis();
|
2019-08-25 09:48:26 +03:00
|
|
|
map.entrySet().removeIf((e) -> e.getValue().time + rateLimitMillis < time);
|
2019-08-09 19:28:08 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
class LimitEntry
|
|
|
|
{
|
|
|
|
long time;
|
|
|
|
int trys;
|
|
|
|
|
|
|
|
public LimitEntry(long time, int trys) {
|
|
|
|
this.time = time;
|
|
|
|
this.trys = trys;
|
|
|
|
}
|
|
|
|
|
|
|
|
public LimitEntry() {
|
|
|
|
time = System.currentTimeMillis();
|
|
|
|
trys = 0;
|
|
|
|
}
|
|
|
|
}
|
2019-08-25 09:48:26 +03:00
|
|
|
protected transient Map<T, LimitEntry> map = new HashMap<>();
|
2019-08-09 19:28:08 +03:00
|
|
|
public boolean check(T address)
|
|
|
|
{
|
2019-08-25 09:48:26 +03:00
|
|
|
if(exclude.contains(address)) return true;
|
2019-08-09 19:28:08 +03:00
|
|
|
LimitEntry entry = map.get(address);
|
|
|
|
if(entry == null)
|
|
|
|
{
|
|
|
|
map.put(address, new LimitEntry());
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
long time = System.currentTimeMillis();
|
2019-08-25 09:48:26 +03:00
|
|
|
if(entry.trys < rateLimit)
|
2019-08-09 19:28:08 +03:00
|
|
|
{
|
|
|
|
entry.trys++;
|
|
|
|
entry.time = time;
|
|
|
|
return true;
|
|
|
|
}
|
2019-08-25 09:48:26 +03:00
|
|
|
if(entry.time + rateLimitMillis < time)
|
2019-08-09 19:28:08 +03:00
|
|
|
{
|
|
|
|
entry.trys = 1;
|
|
|
|
entry.time = time;
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|