1. import java.io.IOException;
  2. import java.util.HashMap;
  3. import java.util.Map;
  4. public class ApiPayloadMetrics {
  5. // Class to store API payload metrics
  6. public static class Metrics {
  7. private long totalRequests;
  8. private long totalBytesSent;
  9. private Map<String, Integer> statusCodes; // Track status code counts
  10. private Map<String, Long> responseTimes; // Track response times for each endpoint
  11. public void incrementTotalRequests() {
  12. totalRequests++;
  13. }
  14. public void addBytesSent(long bytes) {
  15. totalBytesSent += bytes;
  16. }
  17. public void incrementStatusCode(String statusCode) {
  18. statusCodes.put(statusCode, statusCodes.getOrDefault(statusCode, 0) + 1);
  19. }
  20. public void recordResponseTime(String endpoint, long responseTime) {
  21. responseTimes.put(endpoint, responseTime);
  22. }
  23. // Getters for metrics (for reporting/analysis)
  24. public long getTotalRequests() {
  25. return totalRequests;
  26. }
  27. public long getTotalBytesSent() {
  28. return totalBytesSent;
  29. }
  30. public Map<String, Integer> getStatusCodes() {
  31. return statusCodes;
  32. }
  33. public Map<String, Long> getResponseTimes() {
  34. return responseTimes;
  35. }
  36. }
  37. // Method to collect metrics for a single API call
  38. public static Metrics collectMetrics(String endpoint, long bytesSent, int statusCode, long responseTime) {
  39. Metrics metrics = new Metrics();
  40. metrics.incrementTotalRequests();
  41. metrics.addBytesSent(bytesSent);
  42. metrics.incrementStatusCode(String.valueOf(statusCode)); // Convert int to string for map key
  43. metrics.recordResponseTime(endpoint, responseTime);
  44. return metrics;
  45. }
  46. public static void main(String[] args) throws IOException {
  47. //Example Usage
  48. Metrics metrics = collectMetrics("GET /users", 1024, 200, 150);
  49. System.out.println("Total Requests: " + metrics.getTotalRequests());
  50. System.out.println("Total Bytes Sent: " + metrics.getTotalBytesSent());
  51. System.out.println("Status Codes: " + metrics.getStatusCodes());
  52. System.out.println("Response Times: " + metrics.getResponseTimes());
  53. }
  54. }

Add your comment