1607f18267e08e9a4685bad4909b2a285111a307
[aai/gizmo.git] / src / main / java / org / onap / schema / OxmModelValidator.java
1 /**
2  * ============LICENSE_START=======================================================
3  * Gizmo
4  * ================================================================================
5  * Copyright © 2017 AT&T Intellectual Property.
6  * Copyright © 2017 Amdocs
7  * All rights reserved.
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
12  *
13  *    http://www.apache.org/licenses/LICENSE-2.0
14  *
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=========================================================
21  *
22  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
23  */
24 package org.onap.schema;
25
26 import com.google.common.base.CaseFormat;
27 import com.google.gson.JsonElement;
28 import com.google.gson.JsonNull;
29
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;
39
40 import java.util.HashMap;
41 import java.util.Map;
42 import java.util.Set;
43 import javax.ws.rs.core.Response.Status;
44
45 public class OxmModelValidator {
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       throw new CrudException("", Status.NOT_FOUND);
87     }
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");
91
92     for (String key : filter.keySet()) {
93       String keyJavaName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, key);
94       DatabaseMapping mapping = modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName);
95
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);
99       }
100       if (mapping != null) {
101         try {
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
106           // key value
107           continue;
108         }
109       }
110     }
111
112     return result;
113
114   }
115
116   public static String resolveCollectionType(String version, String type) throws CrudException {
117
118     DynamicJAXBContext jaxbContext = null;
119     try {
120       jaxbContext = OxmModelLoader.getContextForVersion(version);
121     } catch (Exception e) {
122       throw new CrudException(e);
123     }
124
125     if (jaxbContext == null) {
126       throw new CrudException("", Status.NOT_FOUND);
127     }
128     // Determine if the Object part is a collection type in the model
129     // definition
130     final DynamicType modelObjectType = jaxbContext.getDynamicType(
131         CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, type)));
132
133     if (modelObjectType == null) {
134       throw new CrudException("", Status.NOT_FOUND);
135     }
136
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
144         // itself
145         throw new CrudException("", Status.NOT_FOUND);
146       }
147       return childObjectType.getDescriptor().getTableName();
148     } else {
149       return modelObjectType.getDescriptor().getTableName();
150     }
151
152   }
153
154   public static Vertex validateIncomingUpsertPayload(String id, String version, String type, JsonElement properties)
155       throws CrudException {
156     
157     try {
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));
162
163       final DynamicType modelObjectType = jaxbContext.getDynamicType(modelObjectClass);
164       final DynamicType reservedType = jaxbContext.getDynamicType("ReservedPropNames");
165
166       Set<Map.Entry<String, JsonElement>> payloadEntriesSet = properties.getAsJsonObject().entrySet();
167
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());
171
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);
176           }
177         }
178
179       }
180
181       Map<String, JsonElement> entriesMap = new HashMap<String, JsonElement>();
182       for (Map.Entry<String, JsonElement> entry : payloadEntriesSet) {
183         entriesMap.put(entry.getKey(), entry.getValue());
184       }
185
186       Vertex.Builder modelVertexBuilder = new Vertex.Builder(type);
187       if (id != null) {
188         modelVertexBuilder.id(id);
189       }
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();
195
196           String keyName = field.getName().substring(0, field.getName().indexOf("/"));
197
198           if (((XMLField) field).isRequired() && !entriesMap.containsKey(keyName) && !defaultValue.isEmpty()) {
199             modelVertexBuilder.property(keyName, CrudServiceUtil.validateFieldType(defaultValue, field.getType()));
200           }
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);
204           }
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);
209           }
210
211           // Set defaults
212           if (!defaultValue.isEmpty() && !entriesMap.containsKey(keyName)) {
213             modelVertexBuilder.property(keyName, CrudServiceUtil.validateFieldType(defaultValue, field.getType()));
214           }
215         }
216       }
217
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("/"));
223
224           if (entriesMap.containsKey(keyName)) {
225             Object value = CrudServiceUtil.validateFieldType(entriesMap.get(keyName).getAsString(), field.getType());
226             modelVertexBuilder.property(keyName, value);
227           }
228         }
229       }
230
231       return modelVertexBuilder.build();
232     } catch (Exception e) {
233       throw new CrudException(e.getMessage(), Status.BAD_REQUEST);
234     }
235   }
236
237   public static Vertex validateIncomingPatchPayload(String id, String version, String type, JsonElement properties,
238       Vertex existingVertex) throws CrudException {
239     try {
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));
244
245       final DynamicType modelObjectType = jaxbContext.getDynamicType(modelObjectClass);
246       final DynamicType reservedType = jaxbContext.getDynamicType("ReservedPropNames");
247
248       Set<Map.Entry<String, JsonElement>> payloadEntriesSet = properties.getAsJsonObject().entrySet();
249
250       // Loop through the payload properties and merge with existing
251       // vertex props
252       for (Map.Entry<String, JsonElement> entry : payloadEntriesSet) {
253
254         String keyJavaName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, entry.getKey());
255
256         DatabaseField field = null;
257         String defaultValue = null;
258
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();
267           defaultValue = "";
268         }
269
270         if (field == null) {
271           throw new CrudException("Invalid field: " + entry.getKey(), Status.BAD_REQUEST);
272         }
273
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);
287         }
288       }
289
290       return existingVertex;
291     } catch (Exception e) {
292       throw new CrudException(e.getMessage(), Status.BAD_REQUEST);
293     }
294   }
295
296   private static DatabaseField getDatabaseField(String fieldName, DynamicType modelObjectType) {
297     for (DatabaseField field : modelObjectType.getDescriptor().getAllFields()) {
298       int ix = field.getName().indexOf("/");
299       if (ix <= 0) {
300         ix = field.getName().length();
301       }
302
303       String keyName = field.getName().substring(0, ix);
304       if (fieldName.equals(keyName)) {
305         return field;
306       }
307     }
308     return null;
309   }
310
311   public static Vertex validateOutgoingPayload(String version, Vertex vertex) { 
312     Vertex.Builder modelVertexBuilder = new Vertex.Builder(vertex.getType()).id(vertex.getId().get());
313
314     try {
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");
322
323       for (String key : vertex.getProperties().keySet()) {
324         DatabaseField field = getDatabaseField(key, modelObjectType);
325         if (field == null) {
326           field = getDatabaseField(key, reservedObjectType);
327         }
328         if (field != null) {
329           modelVertexBuilder.property(key, vertex.getProperties().get(key));
330         }
331       }
332       
333       return modelVertexBuilder.build();
334     } catch (Exception ex) {
335       return vertex;
336     }
337
338   }
339
340 }