import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class ApiPayloadMetrics {
// Class to store API payload metrics
public static class Metrics {
private long totalRequests;
private long totalBytesSent;
private Map<String, Integer> statusCodes; // Track status code counts
private Map<String, Long> responseTimes; // Track response times for each endpoint
public void incrementTotalRequests() {
totalRequests++;
}
public void addBytesSent(long bytes) {
totalBytesSent += bytes;
}
public void incrementStatusCode(String statusCode) {
statusCodes.put(statusCode, statusCodes.getOrDefault(statusCode, 0) + 1);
}
public void recordResponseTime(String endpoint, long responseTime) {
responseTimes.put(endpoint, responseTime);
}
// Getters for metrics (for reporting/analysis)
public long getTotalRequests() {
return totalRequests;
}
public long getTotalBytesSent() {
return totalBytesSent;
}
public Map<String, Integer> getStatusCodes() {
return statusCodes;
}
public Map<String, Long> getResponseTimes() {
return responseTimes;
}
}
// Method to collect metrics for a single API call
public static Metrics collectMetrics(String endpoint, long bytesSent, int statusCode, long responseTime) {
Metrics metrics = new Metrics();
metrics.incrementTotalRequests();
metrics.addBytesSent(bytesSent);
metrics.incrementStatusCode(String.valueOf(statusCode)); // Convert int to string for map key
metrics.recordResponseTime(endpoint, responseTime);
return metrics;
}
public static void main(String[] args) throws IOException {
//Example Usage
Metrics metrics = collectMetrics("GET /users", 1024, 200, 150);
System.out.println("Total Requests: " + metrics.getTotalRequests());
System.out.println("Total Bytes Sent: " + metrics.getTotalBytesSent());
System.out.println("Status Codes: " + metrics.getStatusCodes());
System.out.println("Response Times: " + metrics.getResponseTimes());
}
}
Add your comment