1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27 package gov.nist.secauto.metaschema.schemagen.json.property;
28
29 import com.fasterxml.jackson.databind.node.ArrayNode;
30 import com.fasterxml.jackson.databind.node.JsonNodeFactory;
31 import com.fasterxml.jackson.databind.node.ObjectNode;
32
33 import gov.nist.secauto.metaschema.core.model.INamedInstance;
34 import gov.nist.secauto.metaschema.core.util.ObjectUtils;
35 import gov.nist.secauto.metaschema.schemagen.SchemaGenerationException;
36 import gov.nist.secauto.metaschema.schemagen.json.impl.JsonGenerationState;
37
38 import java.util.Collections;
39 import java.util.LinkedHashMap;
40 import java.util.LinkedHashSet;
41 import java.util.Map;
42 import java.util.Set;
43
44 import edu.umd.cs.findbugs.annotations.NonNull;
45
46 public interface IJsonProperty<I extends INamedInstance> {
47 @NonNull
48 I getInstance();
49
50 @NonNull
51 String getName();
52
53 boolean isRequired();
54
55
56
57
58
59
60
61
62
63
64
65 void generateProperty(
66 @NonNull PropertyCollection properties,
67 @NonNull JsonGenerationState state);
68
69 class PropertyCollection {
70 private final Map<String, ObjectNode> properties;
71 private final Set<String> required;
72
73 public PropertyCollection() {
74 this(new LinkedHashMap<>(), new LinkedHashSet<>());
75 }
76
77 protected PropertyCollection(@NonNull Map<String, ObjectNode> properties, @NonNull Set<String> required) {
78 this.properties = properties;
79 this.required = required;
80 }
81
82 public Map<String, ObjectNode> getProperties() {
83 return Collections.unmodifiableMap(properties);
84 }
85
86 public Set<String> getRequired() {
87 return Collections.unmodifiableSet(required);
88 }
89
90 public void addProperty(@NonNull String name, @NonNull ObjectNode def) {
91 properties.put(name, def);
92 }
93
94 public void addRequired(@NonNull String name) {
95 required.add(name);
96 }
97
98 public PropertyCollection copy() {
99 return new PropertyCollection(new LinkedHashMap<>(properties), new LinkedHashSet<>(required));
100 }
101
102 public void generate(@NonNull ObjectNode obj) {
103 if (!properties.isEmpty()) {
104 ObjectNode propertiesNode = ObjectUtils.notNull(JsonNodeFactory.instance.objectNode());
105 for (Map.Entry<String, ObjectNode> entry : properties.entrySet()) {
106 propertiesNode.set(entry.getKey(), entry.getValue());
107 }
108 obj.set("properties", propertiesNode);
109
110 if (!required.isEmpty()) {
111 ArrayNode requiredNode = ObjectUtils.notNull(JsonNodeFactory.instance.arrayNode());
112 for (String requiredProperty : required) {
113 requiredNode.add(requiredProperty);
114 }
115 obj.set("required", requiredNode);
116 }
117 }
118 }
119 }
120 }