1. import java.util.HashMap;
  2. import java.util.Map;
  3. import java.util.function.Supplier;
  4. public class ApiGuard {
  5. private final Map<String, Object> apiHandlers;
  6. public ApiGuard() {
  7. this.apiHandlers = new HashMap<>();
  8. }
  9. public void registerHandler(String endpoint, Supplier<Object> handler) {
  10. apiHandlers.put(endpoint, handler);
  11. }
  12. public Object execute(String endpoint) {
  13. // Check if the endpoint has a registered handler
  14. if (apiHandlers.containsKey(endpoint)) {
  15. try {
  16. // Execute the handler
  17. return apiHandlers.get(endpoint).get();
  18. } catch (Exception e) {
  19. // Fallback logic in case of handler execution failure
  20. System.err.println("Error executing endpoint " + endpoint + ": " + e.getMessage());
  21. return fallback(); // Return a default value or handle the error
  22. }
  23. } else {
  24. // Endpoint not found, return a default value or handle the error
  25. System.err.println("Endpoint " + endpoint + " not found.");
  26. return fallback();
  27. }
  28. }
  29. // Define the fallback logic
  30. private Object fallback() {
  31. // Replace with your desired fallback behavior
  32. System.out.println("Using fallback logic.");
  33. return "Fallback Value";
  34. }
  35. public static void main(String[] args) {
  36. ApiGuard guard = new ApiGuard();
  37. // Register API handlers
  38. guard.registerHandler("/users", () -> "User data");
  39. guard.registerHandler("/products", () -> "Product catalog");
  40. // Execute API endpoints
  41. System.out.println(guard.execute("/users")); // Output: User data
  42. System.out.println(guard.execute("/products")); // Output: Product catalog
  43. System.out.println(guard.execute("/nonexistent")); // Output: Endpoint not found, then Fallback Value
  44. }
  45. }

Add your comment