import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class TokenFilter {
private final Map<String, Integer> tokenUsage; // Token ID -> Usage count
private final int maxUsage; // Maximum allowed usage per token
private final long timeWindowMillis; // Time window for rate limiting
public TokenFilter(int maxUsage, long timeWindowMillis) {
this.tokenUsage = new ConcurrentHashMap<>();
this.maxUsage = maxUsage;
this.timeWindowMillis = timeWindowMillis;
}
/**
* Filters a list of authentication tokens for maintenance tasks based on rate limiting.
* @param tokens A list of authentication tokens.
* @return A list of valid tokens.
*/
public Iterable<String> filterTokens(Iterable<String> tokens) {
java.util.List<String> validTokens = new java.util.ArrayList<>();
long currentTime = System.currentTimeMillis();
for (String token : tokens) {
if (isTokenAllowed(token, currentTime)) {
validTokens.add(token);
}
}
return validTokens;
}
private boolean isTokenAllowed(String token, long currentTime) {
// Get the current usage count for the token. If it doesn't exist, it's 0.
int currentUsage = tokenUsage.getOrDefault(token, 0);
// Check if the token usage exceeds the maximum allowed.
if (currentUsage >= maxUsage) {
return false; // Rate limited
}
// Increment the usage count for the token.
tokenUsage.put(token, currentUsage + 1);
// Clean up old usage entries.
cleanupOldUsage(currentTime);
return true; // Token is allowed
}
private void cleanupOldUsage(long currentTime) {
// Remove tokens that haven't been used within the time window.
tokenUsage.entrySet().removeIf(entry -> {
long lastUsageTime = entry.getValue();
return (currentTime - lastUsageTime) > timeWindowMillis;
});
}
public static void main(String[] args) {
//Example Usage
TokenFilter filter = new TokenFilter(3, 60000); // Allow 3 uses per minute
java.util.List<String> tokens = java.util.List.of("token1", "token2", "token1", "token3", "token2", "token1", "token4");
java.util.List<String> validTokens = filter.filterTokens(tokens);
System.out.println("Valid Tokens: " + validTokens);
}
}
Add your comment