1. import java.util.HashMap;
  2. import java.util.Map;
  3. import java.util.concurrent.ConcurrentHashMap;
  4. public class TokenFilter {
  5. private final Map<String, Integer> tokenUsage; // Token ID -> Usage count
  6. private final int maxUsage; // Maximum allowed usage per token
  7. private final long timeWindowMillis; // Time window for rate limiting
  8. public TokenFilter(int maxUsage, long timeWindowMillis) {
  9. this.tokenUsage = new ConcurrentHashMap<>();
  10. this.maxUsage = maxUsage;
  11. this.timeWindowMillis = timeWindowMillis;
  12. }
  13. /**
  14. * Filters a list of authentication tokens for maintenance tasks based on rate limiting.
  15. * @param tokens A list of authentication tokens.
  16. * @return A list of valid tokens.
  17. */
  18. public Iterable<String> filterTokens(Iterable<String> tokens) {
  19. java.util.List<String> validTokens = new java.util.ArrayList<>();
  20. long currentTime = System.currentTimeMillis();
  21. for (String token : tokens) {
  22. if (isTokenAllowed(token, currentTime)) {
  23. validTokens.add(token);
  24. }
  25. }
  26. return validTokens;
  27. }
  28. private boolean isTokenAllowed(String token, long currentTime) {
  29. // Get the current usage count for the token. If it doesn't exist, it's 0.
  30. int currentUsage = tokenUsage.getOrDefault(token, 0);
  31. // Check if the token usage exceeds the maximum allowed.
  32. if (currentUsage >= maxUsage) {
  33. return false; // Rate limited
  34. }
  35. // Increment the usage count for the token.
  36. tokenUsage.put(token, currentUsage + 1);
  37. // Clean up old usage entries.
  38. cleanupOldUsage(currentTime);
  39. return true; // Token is allowed
  40. }
  41. private void cleanupOldUsage(long currentTime) {
  42. // Remove tokens that haven't been used within the time window.
  43. tokenUsage.entrySet().removeIf(entry -> {
  44. long lastUsageTime = entry.getValue();
  45. return (currentTime - lastUsageTime) > timeWindowMillis;
  46. });
  47. }
  48. public static void main(String[] args) {
  49. //Example Usage
  50. TokenFilter filter = new TokenFilter(3, 60000); // Allow 3 uses per minute
  51. java.util.List<String> tokens = java.util.List.of("token1", "token2", "token1", "token3", "token2", "token1", "token4");
  52. java.util.List<String> validTokens = filter.filterTokens(tokens);
  53. System.out.println("Valid Tokens: " + validTokens);
  54. }
  55. }

Add your comment