2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright © 2017 AT&T Intellectual Property.
6 * Copyright © 2017 Amdocs
8 * ================================================================================
9 * Licensed under the Apache License, Version 2.0 (the "License");
10 * you may not use this file except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
20 * ============LICENSE_END=========================================================
22 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
24 package org.onap.schema;
26 import com.google.common.base.CaseFormat;
27 import com.google.gson.JsonElement;
28 import com.google.gson.JsonNull;
30 import org.eclipse.persistence.dynamic.DynamicType;
31 import org.eclipse.persistence.internal.helper.DatabaseField;
32 import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext;
33 import org.eclipse.persistence.mappings.DatabaseMapping;
34 import org.eclipse.persistence.oxm.XMLField;
35 import org.onap.aaiutils.oxm.OxmModelLoader;
36 import org.onap.crud.entity.Vertex;
37 import org.onap.crud.exception.CrudException;
38 import org.onap.crud.util.CrudServiceUtil;
40 import java.util.HashMap;
43 import javax.ws.rs.core.Response.Status;
45 public class OxmModelValidator {
46 public enum Metadata {
47 NODE_TYPE("aai-node-type"),
49 CREATED_TS("aai-created-ts"),
50 UPDATED_TS("aai-last-mod-ts"),
51 SOT("source-of-truth"),
52 LAST_MOD_SOT("last-mod-source-of-truth");
54 private final String propName;
56 Metadata(String propName) {
57 this.propName = propName;
60 public String propertyName() {
64 public static boolean isProperty(String property) {
65 for (Metadata meta : Metadata.values()) {
66 if (meta.propName.equals(property)) {
74 public static Map<String, Object> resolveCollectionfilter(String version, String type, Map<String, String> filter)
75 throws CrudException {
77 DynamicJAXBContext jaxbContext = null;
79 jaxbContext = OxmModelLoader.getContextForVersion(version);
80 } catch (Exception e) {
81 throw new CrudException(e);
84 Map<String, Object> result = new HashMap<String, Object>();
85 if (jaxbContext == null) {
86 throw new CrudException("", Status.NOT_FOUND);
88 final DynamicType modelObjectType = jaxbContext.getDynamicType(
89 CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, type)));
90 final DynamicType reservedObjectType = jaxbContext.getDynamicType("ReservedPropNames");
92 for (String key : filter.keySet()) {
93 String keyJavaName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, key);
94 DatabaseMapping mapping = modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName);
96 // Try both the model for the specified type and the reserved properties for our key
97 if (mapping == null) {
98 mapping = reservedObjectType.getDescriptor().getMappingForAttributeName(keyJavaName);
100 if (mapping != null) {
102 Object value = CrudServiceUtil.validateFieldType(filter.get(key), mapping.getField().getType());
103 result.put(key, value);
104 } catch (Exception ex) {
105 // Skip any exceptions thrown while validating the filter
116 public static String resolveCollectionType(String version, String type) throws CrudException {
118 DynamicJAXBContext jaxbContext = null;
120 jaxbContext = OxmModelLoader.getContextForVersion(version);
121 } catch (Exception e) {
122 throw new CrudException(e);
125 if (jaxbContext == null) {
126 throw new CrudException("", Status.NOT_FOUND);
128 // Determine if the Object part is a collection type in the model
130 final DynamicType modelObjectType = jaxbContext.getDynamicType(
131 CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, type)));
133 if (modelObjectType == null) {
134 throw new CrudException("", Status.NOT_FOUND);
137 if (modelObjectType.getDescriptor().getMappings().size() == 1
138 && modelObjectType.getDescriptor().getMappings().get(0).isCollectionMapping()) {
139 String childJavaObjectName = modelObjectType.getDescriptor().getMappings().get(0).getAttributeName();
140 childJavaObjectName = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, childJavaObjectName);
141 final DynamicType childObjectType = jaxbContext.getDynamicType(childJavaObjectName);
142 if (childObjectType == null) {
143 // Should not happen as child object is defined in oxm model
145 throw new CrudException("", Status.NOT_FOUND);
147 return childObjectType.getDescriptor().getTableName();
149 return modelObjectType.getDescriptor().getTableName();
154 public static Vertex validateIncomingUpsertPayload(String id, String version, String type, JsonElement properties)
155 throws CrudException {
158 type = resolveCollectionType(version, type);
159 DynamicJAXBContext jaxbContext = OxmModelLoader.getContextForVersion(version);
160 String modelObjectClass = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL,
161 CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, type));
163 final DynamicType modelObjectType = jaxbContext.getDynamicType(modelObjectClass);
164 final DynamicType reservedType = jaxbContext.getDynamicType("ReservedPropNames");
166 Set<Map.Entry<String, JsonElement>> payloadEntriesSet = properties.getAsJsonObject().entrySet();
168 // loop through input to validate against schema
169 for (Map.Entry<String, JsonElement> entry : payloadEntriesSet) {
170 String keyJavaName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, entry.getKey());
172 // check for valid field
173 if (modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName) == null) {
174 if (reservedType.getDescriptor().getMappingForAttributeName(keyJavaName) == null) {
175 throw new CrudException("Invalid field: " + entry.getKey(), Status.BAD_REQUEST);
181 Map<String, JsonElement> entriesMap = new HashMap<String, JsonElement>();
182 for (Map.Entry<String, JsonElement> entry : payloadEntriesSet) {
183 entriesMap.put(entry.getKey(), entry.getValue());
186 Vertex.Builder modelVertexBuilder = new Vertex.Builder(type);
188 modelVertexBuilder.id(id);
190 for (DatabaseMapping mapping : modelObjectType.getDescriptor().getMappings()) {
191 if (mapping.isAbstractDirectMapping()) {
192 DatabaseField field = mapping.getField();
193 String defaultValue = mapping.getProperties().get("defaultValue") == null ? ""
194 : mapping.getProperties().get("defaultValue").toString();
196 String keyName = field.getName().substring(0, field.getName().indexOf("/"));
198 if (((XMLField) field).isRequired() && !entriesMap.containsKey(keyName) && !defaultValue.isEmpty()) {
199 modelVertexBuilder.property(keyName, CrudServiceUtil.validateFieldType(defaultValue, field.getType()));
201 // if schema field is required and not set then reject
202 if (((XMLField) field).isRequired() && !entriesMap.containsKey(keyName) && defaultValue.isEmpty()) {
203 throw new CrudException("Missing required field: " + keyName, Status.BAD_REQUEST);
205 // If invalid field then reject
206 if (entriesMap.containsKey(keyName)) {
207 Object value = CrudServiceUtil.validateFieldType(entriesMap.get(keyName).getAsString(), field.getType());
208 modelVertexBuilder.property(keyName, value);
212 if (!defaultValue.isEmpty() && !entriesMap.containsKey(keyName)) {
213 modelVertexBuilder.property(keyName, CrudServiceUtil.validateFieldType(defaultValue, field.getType()));
218 // Handle reserved properties
219 for (DatabaseMapping mapping : reservedType.getDescriptor().getMappings()) {
220 if (mapping.isAbstractDirectMapping()) {
221 DatabaseField field = mapping.getField();
222 String keyName = field.getName().substring(0, field.getName().indexOf("/"));
224 if (entriesMap.containsKey(keyName)) {
225 Object value = CrudServiceUtil.validateFieldType(entriesMap.get(keyName).getAsString(), field.getType());
226 modelVertexBuilder.property(keyName, value);
231 return modelVertexBuilder.build();
232 } catch (Exception e) {
233 throw new CrudException(e.getMessage(), Status.BAD_REQUEST);
237 public static Vertex validateIncomingPatchPayload(String id, String version, String type, JsonElement properties,
238 Vertex existingVertex) throws CrudException {
240 type = resolveCollectionType(version, type);
241 DynamicJAXBContext jaxbContext = OxmModelLoader.getContextForVersion(version);
242 String modelObjectClass = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL,
243 CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, type));
245 final DynamicType modelObjectType = jaxbContext.getDynamicType(modelObjectClass);
246 final DynamicType reservedType = jaxbContext.getDynamicType("ReservedPropNames");
248 Set<Map.Entry<String, JsonElement>> payloadEntriesSet = properties.getAsJsonObject().entrySet();
250 // Loop through the payload properties and merge with existing
252 for (Map.Entry<String, JsonElement> entry : payloadEntriesSet) {
254 String keyJavaName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, entry.getKey());
256 DatabaseField field = null;
257 String defaultValue = null;
259 if (modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName) != null) {
260 field = modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName).getField();
261 defaultValue = modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName).getProperties()
262 .get("defaultValue") == null ? ""
263 : modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName).getProperties()
264 .get("defaultValue").toString();
265 } else if (reservedType.getDescriptor().getMappingForAttributeName(keyJavaName) != null) {
266 field = reservedType.getDescriptor().getMappingForAttributeName(keyJavaName).getField();
271 throw new CrudException("Invalid field: " + entry.getKey(), Status.BAD_REQUEST);
274 // check if mandatory field is not set to null
275 if (((XMLField) field).isRequired() && entry.getValue() instanceof JsonNull && !defaultValue.isEmpty()) {
276 existingVertex.getProperties().put(entry.getKey(),
277 CrudServiceUtil.validateFieldType(defaultValue, field.getType()));
278 } else if (((XMLField) field).isRequired() && entry.getValue() instanceof JsonNull && defaultValue.isEmpty()) {
279 throw new CrudException("Mandatory field: " + entry.getKey() + " can't be set to null", Status.BAD_REQUEST);
280 } else if (!((XMLField) field).isRequired() && entry.getValue() instanceof JsonNull
281 && existingVertex.getProperties().containsKey(entry.getKey())) {
282 existingVertex.getProperties().remove(entry.getKey());
283 } else if (!(entry.getValue() instanceof JsonNull)) {
284 // add/update the value if found in existing vertex
285 Object value = CrudServiceUtil.validateFieldType(entry.getValue().getAsString(), field.getType());
286 existingVertex.getProperties().put(entry.getKey(), value);
290 return existingVertex;
291 } catch (Exception e) {
292 throw new CrudException(e.getMessage(), Status.BAD_REQUEST);
296 private static DatabaseField getDatabaseField(String fieldName, DynamicType modelObjectType) {
297 for (DatabaseField field : modelObjectType.getDescriptor().getAllFields()) {
298 int ix = field.getName().indexOf("/");
300 ix = field.getName().length();
303 String keyName = field.getName().substring(0, ix);
304 if (fieldName.equals(keyName)) {
311 public static Vertex validateOutgoingPayload(String version, Vertex vertex) {
312 Vertex.Builder modelVertexBuilder = new Vertex.Builder(vertex.getType()).id(vertex.getId().get());
315 DynamicJAXBContext jaxbContext = OxmModelLoader.getContextForVersion(version);
316 String modelObjectClass = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL,
317 CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL,
318 vertex.getProperties().get(Metadata.NODE_TYPE.propertyName()) != null
319 ? vertex.getProperties().get(Metadata.NODE_TYPE.propertyName()).toString() : vertex.getType()));
320 final DynamicType modelObjectType = jaxbContext.getDynamicType(modelObjectClass);
321 final DynamicType reservedObjectType = jaxbContext.getDynamicType("ReservedPropNames");
323 for (String key : vertex.getProperties().keySet()) {
324 DatabaseField field = getDatabaseField(key, modelObjectType);
326 field = getDatabaseField(key, reservedObjectType);
329 modelVertexBuilder.property(key, vertex.getProperties().get(key));
333 return modelVertexBuilder.build();
334 } catch (Exception ex) {