dda43412c4c58bfbd8eb5da03ef581e27a2901ef
[aai/gizmo.git] / src / main / java / org / onap / schema / OxmModelValidator.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * Copyright © 2017-2018 Amdocs
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *       http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21 package org.onap.schema;
22
23 import com.google.common.base.CaseFormat;
24 import com.google.gson.JsonElement;
25 import com.google.gson.JsonNull;
26
27 import org.eclipse.persistence.dynamic.DynamicType;
28 import org.eclipse.persistence.internal.helper.DatabaseField;
29 import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext;
30 import org.eclipse.persistence.mappings.DatabaseMapping;
31 import org.eclipse.persistence.oxm.XMLField;
32 import org.onap.aaiutils.oxm.OxmModelLoader;
33 import org.onap.crud.entity.Vertex;
34 import org.onap.crud.exception.CrudException;
35 import org.onap.crud.util.CrudServiceUtil;
36
37 import java.util.HashMap;
38 import java.util.Map;
39 import java.util.Set;
40 import javax.ws.rs.core.Response.Status;
41
42 public class OxmModelValidator {
43   public enum Metadata {
44     NODE_TYPE("aai-node-type"),
45     URI("aai-uri"),
46     CREATED_TS("aai-created-ts"),
47     UPDATED_TS("aai-last-mod-ts"),
48     SOT("source-of-truth"),
49     LAST_MOD_SOT("last-mod-source-of-truth");
50
51     private final String propName;
52
53     Metadata(String propName) {
54       this.propName = propName;
55     }
56
57     public String propertyName() {
58       return propName;
59     }
60
61     public static boolean isProperty(String property) {
62       for (Metadata meta : Metadata.values()) {
63         if (meta.propName.equals(property)) {
64           return true;
65         }
66       }
67       return false;
68     }
69   }
70
71   public static Map<String, Object> resolveCollectionfilter(String version, String type, Map<String, String> filter)
72       throws CrudException {
73
74     DynamicJAXBContext jaxbContext = null;
75     try {
76       jaxbContext = OxmModelLoader.getContextForVersion(version);
77     } catch (Exception e) {
78       throw new CrudException(e);
79     }
80
81     Map<String, Object> result = new HashMap<String, Object>();
82     if (jaxbContext == null) {
83       throw new CrudException("", Status.NOT_FOUND);
84     }
85     final DynamicType modelObjectType = jaxbContext.getDynamicType(
86         CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, type)));
87     final DynamicType reservedObjectType = jaxbContext.getDynamicType("ReservedPropNames");
88
89     for (String key : filter.keySet()) {
90       String keyJavaName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, key);
91       DatabaseMapping mapping = modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName);
92
93       // Try both the model for the specified type and the reserved properties for our key
94       if (mapping == null) {
95         mapping = reservedObjectType.getDescriptor().getMappingForAttributeName(keyJavaName);
96       }
97       if (mapping != null) {
98         try {
99           Object value = CrudServiceUtil.validateFieldType(filter.get(key), mapping.getField().getType());
100           result.put(key, value);
101         } catch (Exception ex) {
102           // Skip any exceptions thrown while validating the filter
103           // key value
104           continue;
105         }
106       }
107     }
108
109     return result;
110
111   }
112
113   public static String resolveCollectionType(String version, String type) throws CrudException {
114
115     DynamicJAXBContext jaxbContext = null;
116     try {
117       jaxbContext = OxmModelLoader.getContextForVersion(version);
118     } catch (Exception e) {
119       throw new CrudException(e);
120     }
121
122     if (jaxbContext == null) {
123       throw new CrudException("", Status.NOT_FOUND);
124     }
125     // Determine if the Object part is a collection type in the model
126     // definition
127     final DynamicType modelObjectType = jaxbContext.getDynamicType(
128         CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, type)));
129
130     if (modelObjectType == null) {
131       throw new CrudException("", Status.NOT_FOUND);
132     }
133
134     if (modelObjectType.getDescriptor().getMappings().size() == 1
135         && modelObjectType.getDescriptor().getMappings().get(0).isCollectionMapping()) {
136       String childJavaObjectName = modelObjectType.getDescriptor().getMappings().get(0).getAttributeName();
137       childJavaObjectName = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, childJavaObjectName);
138       final DynamicType childObjectType = jaxbContext.getDynamicType(childJavaObjectName);
139       if (childObjectType == null) {
140         // Should not happen as child object is defined in oxm model
141         // itself
142         throw new CrudException("", Status.NOT_FOUND);
143       }
144       return childObjectType.getDescriptor().getTableName();
145     } else {
146       return modelObjectType.getDescriptor().getTableName();
147     }
148
149   }
150
151   public static Vertex validateIncomingUpsertPayload(String id, String version, String type, JsonElement properties)
152       throws CrudException {
153     
154     try {
155       type = resolveCollectionType(version, type);
156       DynamicJAXBContext jaxbContext = OxmModelLoader.getContextForVersion(version);
157       String modelObjectClass = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL,
158           CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, type));
159
160       final DynamicType modelObjectType = jaxbContext.getDynamicType(modelObjectClass);
161       final DynamicType reservedType = jaxbContext.getDynamicType("ReservedPropNames");
162
163       Set<Map.Entry<String, JsonElement>> payloadEntriesSet = properties.getAsJsonObject().entrySet();
164
165       // loop through input to validate against schema
166       for (Map.Entry<String, JsonElement> entry : payloadEntriesSet) {
167         String keyJavaName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, entry.getKey());
168
169         // check for valid field
170         if (modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName) == null) {
171           if (reservedType.getDescriptor().getMappingForAttributeName(keyJavaName) == null) {
172             throw new CrudException("Invalid field: " + entry.getKey(), Status.BAD_REQUEST);
173           }
174         }
175
176       }
177
178       Map<String, JsonElement> entriesMap = new HashMap<String, JsonElement>();
179       for (Map.Entry<String, JsonElement> entry : payloadEntriesSet) {
180         entriesMap.put(entry.getKey(), entry.getValue());
181       }
182
183       Vertex.Builder modelVertexBuilder = new Vertex.Builder(type);
184       if (id != null) {
185         modelVertexBuilder.id(id);
186       }
187       for (DatabaseMapping mapping : modelObjectType.getDescriptor().getMappings()) {
188         if (mapping.isAbstractDirectMapping()) {
189           DatabaseField field = mapping.getField();
190           String defaultValue = mapping.getProperties().get("defaultValue") == null ? ""
191               : mapping.getProperties().get("defaultValue").toString();
192
193           String keyName = field.getName().substring(0, field.getName().indexOf("/"));
194
195           if (((XMLField) field).isRequired() && !entriesMap.containsKey(keyName) && !defaultValue.isEmpty()) {
196             modelVertexBuilder.property(keyName, CrudServiceUtil.validateFieldType(defaultValue, field.getType()));
197           }
198           // if schema field is required and not set then reject
199           if (((XMLField) field).isRequired() && !entriesMap.containsKey(keyName) && defaultValue.isEmpty()) {
200             throw new CrudException("Missing required field: " + keyName, Status.BAD_REQUEST);
201           }
202           // If invalid field then reject
203           if (entriesMap.containsKey(keyName)) {
204             Object value = CrudServiceUtil.validateFieldType(entriesMap.get(keyName).getAsString(), field.getType());
205             modelVertexBuilder.property(keyName, value);
206           }
207
208           // Set defaults
209           if (!defaultValue.isEmpty() && !entriesMap.containsKey(keyName)) {
210             modelVertexBuilder.property(keyName, CrudServiceUtil.validateFieldType(defaultValue, field.getType()));
211           }
212         }
213       }
214
215       // Handle reserved properties
216       for (DatabaseMapping mapping : reservedType.getDescriptor().getMappings()) {
217         if (mapping.isAbstractDirectMapping()) {
218           DatabaseField field = mapping.getField();
219           String keyName = field.getName().substring(0, field.getName().indexOf("/"));
220
221           if (entriesMap.containsKey(keyName)) {
222             Object value = CrudServiceUtil.validateFieldType(entriesMap.get(keyName).getAsString(), field.getType());
223             modelVertexBuilder.property(keyName, value);
224           }
225         }
226       }
227
228       return modelVertexBuilder.build();
229     } catch (Exception e) {
230       throw new CrudException(e.getMessage(), Status.BAD_REQUEST);
231     }
232   }
233
234   public static Vertex validateIncomingPatchPayload(String id, String version, String type, JsonElement properties,
235       Vertex existingVertex) throws CrudException {
236     try {
237       type = resolveCollectionType(version, type);
238       DynamicJAXBContext jaxbContext = OxmModelLoader.getContextForVersion(version);
239       String modelObjectClass = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL,
240           CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, type));
241
242       final DynamicType modelObjectType = jaxbContext.getDynamicType(modelObjectClass);
243       final DynamicType reservedType = jaxbContext.getDynamicType("ReservedPropNames");
244
245       Set<Map.Entry<String, JsonElement>> payloadEntriesSet = properties.getAsJsonObject().entrySet();
246
247       // Loop through the payload properties and merge with existing
248       // vertex props
249       for (Map.Entry<String, JsonElement> entry : payloadEntriesSet) {
250
251         String keyJavaName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, entry.getKey());
252
253         DatabaseField field = null;
254         String defaultValue = null;
255
256         if (modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName) != null) {
257           field = modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName).getField();
258           defaultValue = modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName).getProperties()
259               .get("defaultValue") == null ? ""
260                   : modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName).getProperties()
261                       .get("defaultValue").toString();
262         } else if (reservedType.getDescriptor().getMappingForAttributeName(keyJavaName) != null) {
263           field = reservedType.getDescriptor().getMappingForAttributeName(keyJavaName).getField();
264           defaultValue = "";
265         }
266
267         if (field == null) {
268           throw new CrudException("Invalid field: " + entry.getKey(), Status.BAD_REQUEST);
269         }
270
271         // check if mandatory field is not set to null
272         if (((XMLField) field).isRequired() && entry.getValue() instanceof JsonNull && !defaultValue.isEmpty()) {
273           existingVertex.getProperties().put(entry.getKey(),
274               CrudServiceUtil.validateFieldType(defaultValue, field.getType()));
275         } else if (((XMLField) field).isRequired() && entry.getValue() instanceof JsonNull && defaultValue.isEmpty()) {
276           throw new CrudException("Mandatory field: " + entry.getKey() + " can't be set to null", Status.BAD_REQUEST);
277         } else if (!((XMLField) field).isRequired() && entry.getValue() instanceof JsonNull
278             && existingVertex.getProperties().containsKey(entry.getKey())) {
279           existingVertex.getProperties().remove(entry.getKey());
280         } else if (!(entry.getValue() instanceof JsonNull)) {
281           // add/update the value if found in existing vertex
282           Object value = CrudServiceUtil.validateFieldType(entry.getValue().getAsString(), field.getType());
283           existingVertex.getProperties().put(entry.getKey(), value);
284         }
285       }
286
287       return existingVertex;
288     } catch (Exception e) {
289       throw new CrudException(e.getMessage(), Status.BAD_REQUEST);
290     }
291   }
292
293   private static DatabaseField getDatabaseField(String fieldName, DynamicType modelObjectType) {
294     for (DatabaseField field : modelObjectType.getDescriptor().getAllFields()) {
295       int ix = field.getName().indexOf("/");
296       if (ix <= 0) {
297         ix = field.getName().length();
298       }
299
300       String keyName = field.getName().substring(0, ix);
301       if (fieldName.equals(keyName)) {
302         return field;
303       }
304     }
305     return null;
306   }
307
308   public static Vertex validateOutgoingPayload(String version, Vertex vertex) { 
309     Vertex.Builder modelVertexBuilder = new Vertex.Builder(vertex.getType()).id(vertex.getId().get());
310
311     try {
312       DynamicJAXBContext jaxbContext = OxmModelLoader.getContextForVersion(version);
313       String modelObjectClass = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL,
314           CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL,
315               vertex.getProperties().get(Metadata.NODE_TYPE.propertyName()) != null
316                   ? vertex.getProperties().get(Metadata.NODE_TYPE.propertyName()).toString() : vertex.getType()));
317       final DynamicType modelObjectType = jaxbContext.getDynamicType(modelObjectClass);
318       final DynamicType reservedObjectType = jaxbContext.getDynamicType("ReservedPropNames");
319
320       for (String key : vertex.getProperties().keySet()) {
321         DatabaseField field = getDatabaseField(key, modelObjectType);
322         if (field == null) {
323           field = getDatabaseField(key, reservedObjectType);
324         }
325         if (field != null) {
326           modelVertexBuilder.property(key, vertex.getProperties().get(key));
327         }
328       }
329       
330       return modelVertexBuilder.build();
331     } catch (Exception ex) {
332       return vertex;
333     }
334
335   }
336
337 }