Untitled
unknown
java
2 years ago
2.3 kB
5
Indexable
import java.util.*;
import java.util.regex.*;
import java.util.stream.Collectors;
class Result {
public static List<Integer> validateRequests(List<String> blacklisted_ips, List<String> requests) {
// Convert wildcard IPs to regex patterns
List<Pattern> patterns = blacklisted_ips.stream()
.map(ip -> ip.replace("*", ".*"))
.map(Pattern::compile)
.collect(Collectors.toList());
// LinkedHashMap to maintain the order of IPs and their valid request counts
Map<String, Integer> validRequestCounts = new LinkedHashMap<>();
// Initialize the result list with the same size as requests
List<Integer> results = new ArrayList<>(Collections.nCopies(requests.size(), 0));
for (int i = 0; i < requests.size(); i++) {
String requestIP = requests.get(i);
boolean isBlocked = false;
// Check against blacklisted IPs
for (Pattern pattern : patterns) {
if (pattern.matcher(requestIP).find()) {
isBlocked = true;
break;
}
}
// Check the rate limit only if the request is not blocked by the blacklist
if (!isBlocked) {
// If the IP is new or too old (not in the last 5 seconds), reset the count
validRequestCounts.putIfAbsent(requestIP, 0);
// Iterate over the entries and decrease the count for stale timestamps
validRequestCounts.entrySet().removeIf(entry -> i - entry.getValue() >= 5);
// Check the request count for the current IP
if (validRequestCounts.get(requestIP) >= 2) {
isBlocked = true; // Block if more than 2 requests in the last 5 seconds
} else {
// Increase the valid request count
validRequestCounts.merge(requestIP, 1, Integer::sum);
}
}
// Record the result for the current request
results.set(i, isBlocked ? 1 : 0);
}
return results;
}
}
// The rest of the code remains the same as before
Editor is loading...
Leave a Comment