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