1. import org.json.JSONObject;
  2. public class JsonResponseExtender {
  3. /**
  4. * Extends the existing JSON response logic for isolated environments.
  5. * Adds environment-specific information to the JSON response.
  6. *
  7. * @param originalResponse The original JSON response as a JSONObject.
  8. * @param environmentName The name of the isolated environment (e.g., "dev", "staging").
  9. * @return The extended JSON response as a JSONObject. Returns null if the input is invalid.
  10. */
  11. public static JSONObject extendResponseForIsolatedEnvironment(JSONObject originalResponse, String environmentName) {
  12. // Check if the input is a valid JSONObject
  13. if (originalResponse == null || !(originalResponse instanceof JSONObject)) {
  14. System.err.println("Invalid input: originalResponse must be a JSONObject.");
  15. return null;
  16. }
  17. // Create a copy of the original response to avoid modifying the original
  18. JSONObject extendedResponse = originalResponse.copy();
  19. // Add environment-specific information to the extended response
  20. try {
  21. extendedResponse.put("environment", environmentName); // Add the environment name
  22. extendedResponse.put("environment_details", "Isolated environment"); // Add a general description
  23. extendedResponse.put("timestamp", System.currentTimeMillis()); // Add a timestamp
  24. } catch (Exception e) {
  25. System.err.println("Error adding environment details: " + e.getMessage());
  26. return null;
  27. }
  28. return extendedResponse;
  29. }
  30. public static void main(String[] args) {
  31. // Example Usage
  32. JSONObject originalResponse = new JSONObject();
  33. originalResponse.put("status", "success");
  34. originalResponse.put("data", "some data");
  35. String environment = "dev";
  36. JSONObject extendedResponse = extendResponseForIsolatedEnvironment(originalResponse, environment);
  37. if (extendedResponse != null) {
  38. System.out.println(extendedResponse.toString(2)); // Print the extended JSON with indentation
  39. }
  40. }
  41. }

Add your comment