1 package cn.home1.oss.environment.configlint;
2
3 import org.slf4j.Logger;
4 import org.slf4j.LoggerFactory;
5
6 import java.io.File;
7 import java.util.HashMap;
8 import java.util.Map;
9
10
11
12
13 public class ValidateRunner {
14
15 private static final Logger log = LoggerFactory.getLogger(PropertyValidator.class);
16
17 private Map<String, FileValidator> validators = new HashMap<>();
18 private Map<String, String> fileValidateMappings = new HashMap<>();
19
20 public ValidateRunner() {
21
22 this.fileValidateMappings.put("yml", "YmlValidator");
23 this.fileValidateMappings.put("yaml", "YmlValidator");
24 this.fileValidateMappings.put("property", "PropertyValidator");
25 this.fileValidateMappings.put("properties", "PropertyValidator");
26 }
27
28 public int process(final String... args) {
29 int status = 0;
30 for (final String path : args) {
31 final String suffix = verify(path);
32 if (suffix == null) {
33 continue;
34 }
35
36 try {
37 final FileValidator validator = this.getValidator(suffix);
38 if (validator != null) {
39 validator.validate(path);
40 } else {
41 log.warn("validator for {} not found.", path);
42 status = 1;
43 }
44 } catch (final Exception ex) {
45 log.warn("文件校验错误 {}, {}", path, ex.getMessage(), ex);
46 status = 1;
47 }
48 }
49
50 return status;
51 }
52
53 private String verify(final String path) {
54 final String fileSuffix = path.substring(path.lastIndexOf('.') + 1).toLowerCase();
55 if (!this.fileValidateMappings.containsKey(fileSuffix)) {
56 log.warn("不支持的文件类型: {}", path);
57 return null;
58 }
59
60 final File file = new File(path);
61 if (!file.isFile()) {
62 log.warn("指定的path不是文件: {}", path);
63 return null;
64 }
65 if (!file.exists()) {
66 log.warn("文件不存在: {}", path);
67 return null;
68 }
69
70 return fileSuffix;
71 }
72
73 private FileValidator getValidator(final String suffix) {
74 final String clsName = this.getClass().getPackage().getName() + "." + this.fileValidateMappings.get(suffix);
75 FileValidator validator = this.validators.get(clsName);
76 if (validator == null) {
77 Class<?> cls;
78 try {
79 cls = Class.forName(clsName);
80 validator = (FileValidator) cls.newInstance();
81 this.validators.put(clsName, validator);
82 } catch (final Exception ex) {
83 log.warn("error get validator, suffix {}", suffix, ex);
84 }
85 }
86
87 return validator;
88 }
89 }