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