1. import java.util.HashMap;
  2. import java.util.Map;
  3. public class ConfigValidator {
  4. /**
  5. * Validates user-provided configuration parameters.
  6. *
  7. * @param config A map containing the configuration parameters.
  8. * Keys are parameter names (strings), values are parameter values.
  9. * @return A map containing validation errors. If no errors, returns an empty map.
  10. */
  11. public static Map<String, String> validateConfig(Map<String, String> config) {
  12. Map<String, String> errors = new HashMap<>();
  13. // Example validation rules (customize as needed)
  14. if (config == null) {
  15. errors.put("overall", "Configuration cannot be null.");
  16. return errors;
  17. }
  18. if (config.get("appName") == null || config.get("appName").trim().isEmpty()) {
  19. errors.put("appName", "Application name cannot be empty.");
  20. }
  21. if (config.get("port") == null || !config.get("port").matches("\\d+")) {
  22. errors.put("port", "Port must be a number.");
  23. }
  24. if (config.get("debug") != null && !config.get("debug").equals("true") && !config.get("debug").equals("false")) {
  25. errors.put("debug", "Debug value must be 'true' or 'false'.");
  26. }
  27. if (config.get("databaseUrl") == null || config.get("databaseUrl").trim().isEmpty()) {
  28. errors.put("databaseUrl", "Database URL cannot be empty.");
  29. }
  30. return errors;
  31. }
  32. public static void main(String[] args){
  33. //Example usage
  34. Map<String, String> config1 = new HashMap<>();
  35. config1.put("appName", "MyApplication");
  36. config1.put("port", "8080");
  37. config1.put("debug", "true");
  38. config1.put("databaseUrl", "jdbc:mysql://localhost:3306/mydb");
  39. Map<String, String> errors1 = validateConfig(config1);
  40. System.out.println("Validation errors: " + errors1);
  41. Map<String, String> config2 = new HashMap<>();
  42. config2.put("appName", "");
  43. config2.put("port", "abc");
  44. config2.put("debug", "maybe");
  45. Map<String, String> errors2 = validateConfig(config2);
  46. System.out.println("Validation errors: " + errors2);
  47. }
  48. }

Add your comment