Fix Fortify scan violation
[aai/gizmo.git] / src / main / java / org / onap / schema / validation / 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.validation;
22
23 import java.util.HashMap;
24 import java.util.Map;
25 import java.util.Set;
26 import javax.ws.rs.core.Response.Status;
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.aai.cl.api.Logger;
33 import org.onap.aai.cl.eelf.LoggerFactory;
34 import org.onap.crud.entity.Vertex;
35 import org.onap.crud.exception.CrudException;
36 import org.onap.crud.logging.CrudServiceMsgs;
37 import org.onap.crud.util.CrudServiceConstants;
38 import org.onap.crud.util.CrudServiceUtil;
39 import org.onap.schema.OxmModelLoader;
40 import com.google.common.base.CaseFormat;
41 import com.google.gson.JsonElement;
42 import com.google.gson.JsonNull;
43
44 public class OxmModelValidator {
45   private static Logger logger = LoggerFactory.getInstance().getLogger(OxmModelValidator.class.getName());
46
47   public enum Metadata {
48     NODE_TYPE("aai-node-type"),
49     URI("aai-uri"),
50     CREATED_TS("aai-created-ts"),
51     UPDATED_TS("aai-last-mod-ts"),
52     SOT("source-of-truth"),
53     LAST_MOD_SOT("last-mod-source-of-truth");
54
55     private final String propName;
56
57     Metadata(String propName) {
58       this.propName = propName;
59     }
60
61     public String propertyName() {
62       return propName;
63     }
64
65     public static boolean isProperty(String property) {
66       for (Metadata meta : Metadata.values()) {
67         if (meta.propName.equals(property)) {
68           return true;
69         }
70       }
71       return false;
72     }
73   }
74
75   public static Map<String, Object> resolveCollectionfilter(String version, String type, Map<String, String> filter)
76       throws CrudException {
77
78     DynamicJAXBContext jaxbContext = null;
79     try {
80       jaxbContext = OxmModelLoader.getContextForVersion(version);
81     } catch (Exception e) {
82       throw new CrudException(e);
83     }
84
85     Map<String, Object> result = new HashMap<String, Object>();
86     if (jaxbContext == null) {
87       logger.error(CrudServiceMsgs.OXM_LOAD_ERROR, "Error loading oxm model: " + version);
88       throw new CrudException("Error loading oxm model: " + version, Status.NOT_FOUND);
89     }
90     final DynamicType modelObjectType = jaxbContext.getDynamicType(
91         CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, type)));
92     final DynamicType reservedObjectType = jaxbContext.getDynamicType("ReservedPropNames");
93
94     for (String key : filter.keySet()) {
95         if ((key == CrudServiceConstants.CRD_RESERVED_VERSION )  || key == CrudServiceConstants.CRD_RESERVED_NODE_TYPE ) {
96           result.put ( key, filter.get ( key ) );
97           continue;
98         }
99       String keyJavaName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, key);
100       DatabaseMapping mapping = modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName);
101
102       // Try both the model for the specified type and the reserved properties for our key
103       if (mapping == null) {
104         mapping = reservedObjectType.getDescriptor().getMappingForAttributeName(keyJavaName);
105       }
106       if (mapping != null) {
107         try {
108           Object value = CrudServiceUtil.validateFieldType(filter.get(key), mapping.getField().getType());
109           result.put(key, value);
110         } catch (Exception ex) {
111           // Skip any exceptions thrown while validating the filter
112           // key value
113           continue;
114         }
115       }
116     }
117
118     return result;
119
120   }
121
122   public static String resolveCollectionType(String version, String type) throws CrudException {
123
124     DynamicJAXBContext jaxbContext = null;
125     try {
126       jaxbContext = OxmModelLoader.getContextForVersion(version);
127     } catch (CrudException ce) {
128       throw new CrudException(ce.getMessage(), ce.getHttpStatus());
129     } catch (Exception e) {
130       throw new CrudException(e);
131     }
132
133     if (jaxbContext == null) {
134       logger.error(CrudServiceMsgs.OXM_LOAD_ERROR, "Error loading oxm model: " + version);
135       throw new CrudException("Error loading oxm model: " + version, Status.NOT_FOUND);
136     }
137     // Determine if the Object part is a collection type in the model
138     // definition
139     final DynamicType modelObjectType = jaxbContext.getDynamicType(
140         CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, type)));
141
142     if (modelObjectType == null) {
143       logger.error(CrudServiceMsgs.INVALID_OXM_FILE, "Object of collection type not found: " + type);
144       throw new CrudException("Object of collection type not found: " + type, Status.NOT_FOUND);
145     }
146
147     if (modelObjectType.getDescriptor().getMappings().size() == 1
148         && modelObjectType.getDescriptor().getMappings().get(0).isCollectionMapping()) {
149       String childJavaObjectName = modelObjectType.getDescriptor().getMappings().get(0).getAttributeName();
150       childJavaObjectName = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, childJavaObjectName);
151       final DynamicType childObjectType = jaxbContext.getDynamicType(childJavaObjectName);
152       if (childObjectType == null) {
153         // Should not happen as child object is defined in oxm model itself
154         logger.error(CrudServiceMsgs.INVALID_OXM_FILE, "Child Object Type for Java Object not found: " + childJavaObjectName);
155         throw new CrudException("Child Object Type for Java Object not found: " + childJavaObjectName, Status.NOT_FOUND);
156       }
157       return childObjectType.getDescriptor().getTableName();
158     } else {
159       return modelObjectType.getDescriptor().getTableName();
160     }
161
162   }
163
164   public static Vertex validateIncomingUpsertPayload(String id, String version, String type, JsonElement properties)
165       throws CrudException {
166
167     try {
168       type = resolveCollectionType(version, type);
169       DynamicJAXBContext jaxbContext = OxmModelLoader.getContextForVersion(version);
170       String modelObjectClass = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL,
171           CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, type));
172
173       final DynamicType modelObjectType = jaxbContext.getDynamicType(modelObjectClass);
174       final DynamicType reservedType = jaxbContext.getDynamicType("ReservedPropNames");
175
176       Set<Map.Entry<String, JsonElement>> payloadEntriesSet = properties.getAsJsonObject().entrySet();
177
178       // loop through input to validate against schema
179       for (Map.Entry<String, JsonElement> entry : payloadEntriesSet) {
180         String keyJavaName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, entry.getKey());
181
182         // check for valid field
183         if (modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName) == null) {
184           if (reservedType.getDescriptor().getMappingForAttributeName(keyJavaName) == null) {
185             throw new CrudException("Invalid field: " + entry.getKey(), Status.BAD_REQUEST);
186           }
187         }
188
189       }
190
191       Map<String, JsonElement> entriesMap = new HashMap<String, JsonElement>();
192       for (Map.Entry<String, JsonElement> entry : payloadEntriesSet) {
193         entriesMap.put(entry.getKey(), entry.getValue());
194       }
195
196       Vertex.Builder modelVertexBuilder = new Vertex.Builder(type);
197       if (id != null) {
198         modelVertexBuilder.id(id);
199       }
200       for (DatabaseMapping mapping : modelObjectType.getDescriptor().getMappings()) {
201         if (mapping.isAbstractDirectMapping()) {
202           DatabaseField field = mapping.getField();
203           String defaultValue = mapping.getProperties().get("defaultValue") == null ? ""
204               : mapping.getProperties().get("defaultValue").toString();
205
206           String keyName = field.getName().substring(0, field.getName().indexOf("/"));
207
208           if (((XMLField) field).isRequired() && !entriesMap.containsKey(keyName) && !defaultValue.isEmpty()) {
209             modelVertexBuilder.property(keyName, CrudServiceUtil.validateFieldType(defaultValue, field.getType()));
210           }
211           // if schema field is required and not set then reject
212           if (((XMLField) field).isRequired() && !entriesMap.containsKey(keyName) && defaultValue.isEmpty()) {
213             throw new CrudException("Missing required field: " + keyName, Status.BAD_REQUEST);
214           }
215           // If invalid field then reject
216           if (entriesMap.containsKey(keyName)) {
217             Object value = CrudServiceUtil.validateFieldType(entriesMap.get(keyName).getAsString(), field.getType());
218             modelVertexBuilder.property(keyName, value);
219           }
220
221           // Set defaults
222           if (!defaultValue.isEmpty() && !entriesMap.containsKey(keyName)) {
223             modelVertexBuilder.property(keyName, CrudServiceUtil.validateFieldType(defaultValue, field.getType()));
224           }
225         }
226       }
227
228       // Handle reserved properties
229       for (DatabaseMapping mapping : reservedType.getDescriptor().getMappings()) {
230         if (mapping.isAbstractDirectMapping()) {
231           DatabaseField field = mapping.getField();
232           String keyName = field.getName().substring(0, field.getName().indexOf("/"));
233
234           if (entriesMap.containsKey(keyName)) {
235             Object value = CrudServiceUtil.validateFieldType(entriesMap.get(keyName).getAsString(), field.getType());
236             modelVertexBuilder.property(keyName, value);
237           }
238         }
239       }
240
241       return modelVertexBuilder.build();
242     } catch (CrudException ce) {
243       throw new CrudException(ce.getMessage(), ce.getHttpStatus());
244     } catch (Exception e) {
245       throw new CrudException(e.getMessage(), Status.BAD_REQUEST);
246     }
247   }
248
249   public static Vertex validateIncomingPatchPayload(String id, String version, String type, JsonElement properties,
250       Vertex existingVertex) throws CrudException {
251     try {
252       type = resolveCollectionType(version, type);
253       DynamicJAXBContext jaxbContext = OxmModelLoader.getContextForVersion(version);
254       String modelObjectClass = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL,
255           CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, type));
256
257       final DynamicType modelObjectType = jaxbContext.getDynamicType(modelObjectClass);
258       final DynamicType reservedType = jaxbContext.getDynamicType("ReservedPropNames");
259
260       Set<Map.Entry<String, JsonElement>> payloadEntriesSet = properties.getAsJsonObject().entrySet();
261
262       // Loop through the payload properties and merge with existing
263       // vertex props
264       for (Map.Entry<String, JsonElement> entry : payloadEntriesSet) {
265
266         String keyJavaName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, entry.getKey());
267
268         DatabaseField field = null;
269         String defaultValue = null;
270
271         if (modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName) != null) {
272           field = modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName).getField();
273           defaultValue = modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName).getProperties()
274               .get("defaultValue") == null ? ""
275                   : modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName).getProperties()
276                       .get("defaultValue").toString();
277         } else if (reservedType.getDescriptor().getMappingForAttributeName(keyJavaName) != null) {
278           field = reservedType.getDescriptor().getMappingForAttributeName(keyJavaName).getField();
279           defaultValue = "";
280         }
281
282         if (field == null) {
283           throw new CrudException("Invalid field: " + entry.getKey(), Status.BAD_REQUEST);
284         }
285
286         // check if mandatory field is not set to null
287         if (((XMLField) field).isRequired() && entry.getValue() instanceof JsonNull && !defaultValue.isEmpty()) {
288           existingVertex.getProperties().put(entry.getKey(),
289               CrudServiceUtil.validateFieldType(defaultValue, field.getType()));
290         } else if (((XMLField) field).isRequired() && entry.getValue() instanceof JsonNull && defaultValue.isEmpty()) {
291           throw new CrudException("Mandatory field: " + entry.getKey() + " can't be set to null", Status.BAD_REQUEST);
292         } else if (!((XMLField) field).isRequired() && entry.getValue() instanceof JsonNull
293             && existingVertex.getProperties().containsKey(entry.getKey())) {
294           existingVertex.getProperties().remove(entry.getKey());
295         } else if (!(entry.getValue() instanceof JsonNull)) {
296           // add/update the value if found in existing vertex
297           Object value = CrudServiceUtil.validateFieldType(entry.getValue().getAsString(), field.getType());
298           existingVertex.getProperties().put(entry.getKey(), value);
299         }
300       }
301
302       return existingVertex;
303     } catch (Exception e) {
304       throw new CrudException(e.getMessage(), Status.BAD_REQUEST);
305     }
306   }
307
308   private static DatabaseField getDatabaseField(String fieldName, DynamicType modelObjectType) {
309     for (DatabaseField field : modelObjectType.getDescriptor().getAllFields()) {
310       int ix = field.getName().indexOf("/");
311       if (ix <= 0) {
312         ix = field.getName().length();
313       }
314
315       String keyName = field.getName().substring(0, ix);
316       if (fieldName.equals(keyName)) {
317         return field;
318       }
319     }
320     return null;
321   }
322
323   public static Vertex validateOutgoingPayload(String version, Vertex vertex) {
324     Vertex.Builder modelVertexBuilder = new Vertex.Builder(vertex.getType()).id(vertex.getId().get());
325
326     try {
327       DynamicJAXBContext jaxbContext = OxmModelLoader.getContextForVersion(version);
328       String modelObjectClass = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL,
329           CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL,
330               vertex.getProperties().get(Metadata.NODE_TYPE.propertyName()) != null
331                   ? vertex.getProperties().get(Metadata.NODE_TYPE.propertyName()).toString() : vertex.getType()));
332       final DynamicType modelObjectType = jaxbContext.getDynamicType(modelObjectClass);
333       final DynamicType reservedObjectType = jaxbContext.getDynamicType("ReservedPropNames");
334
335       for (String key : vertex.getProperties().keySet()) {
336         DatabaseField field = getDatabaseField(key, modelObjectType);
337         if (field == null) {
338           field = getDatabaseField(key, reservedObjectType);
339         }
340         if (field != null) {
341           modelVertexBuilder.property(key, vertex.getProperties().get(key));
342         }
343       }
344
345       return modelVertexBuilder.build();
346     } catch (Exception ex) {
347       return vertex;
348     }
349
350   }
351
352 }