6260f83e24c8ce057c304d85eb712755a8ac724e
[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
91     for (String key : filter.keySet()) {
92       String keyJavaName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, key);
93       if (modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName) != null) {
94         try {
95           DatabaseMapping mapping = modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName);
96           Object value = CrudServiceUtil.validateFieldType(filter.get(key), mapping.getField().getType());
97           result.put(key, value);
98         } catch (Exception ex) {
99           // Skip any exceptions thrown while validating the filter
100           // key value
101           continue;
102         }
103       }
104     }
105
106     return result;
107
108   }
109
110   public static String resolveCollectionType(String version, String type) throws CrudException {
111
112     DynamicJAXBContext jaxbContext = null;
113     try {
114       jaxbContext = OxmModelLoader.getContextForVersion(version);
115     } catch (Exception e) {
116       throw new CrudException(e);
117     }
118
119     if (jaxbContext == null) {
120       throw new CrudException("", Status.NOT_FOUND);
121     }
122     // Determine if the Object part is a collection type in the model
123     // definition
124     final DynamicType modelObjectType = jaxbContext.getDynamicType(
125         CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, type)));
126
127     if (modelObjectType == null) {
128       throw new CrudException("", Status.NOT_FOUND);
129     }
130
131     if (modelObjectType.getDescriptor().getMappings().size() == 1
132         && modelObjectType.getDescriptor().getMappings().get(0).isCollectionMapping()) {
133       String childJavaObjectName = modelObjectType.getDescriptor().getMappings().get(0).getAttributeName();
134       childJavaObjectName = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, childJavaObjectName);
135       final DynamicType childObjectType = jaxbContext.getDynamicType(childJavaObjectName);
136       if (childObjectType == null) {
137         // Should not happen as child object is defined in oxm model
138         // itself
139         throw new CrudException("", Status.NOT_FOUND);
140       }
141       return childObjectType.getDescriptor().getTableName();
142     } else {
143       return modelObjectType.getDescriptor().getTableName();
144     }
145
146   }
147
148   public static Vertex validateIncomingUpsertPayload(String id, String version, String type, JsonElement properties)
149       throws CrudException {
150     
151     try {
152       type = resolveCollectionType(version, type);
153       DynamicJAXBContext jaxbContext = OxmModelLoader.getContextForVersion(version);
154       String modelObjectClass = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL,
155           CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, type));
156
157       final DynamicType modelObjectType = jaxbContext.getDynamicType(modelObjectClass);
158       final DynamicType reservedType = jaxbContext.getDynamicType("ReservedPropNames");
159
160       Set<Map.Entry<String, JsonElement>> payloadEntriesSet = properties.getAsJsonObject().entrySet();
161
162       // loop through input to validate against schema
163       for (Map.Entry<String, JsonElement> entry : payloadEntriesSet) {
164         String keyJavaName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, entry.getKey());
165
166         // check for valid field
167         if (modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName) == null) {
168           if (reservedType.getDescriptor().getMappingForAttributeName(keyJavaName) == null) {
169             throw new CrudException("Invalid field: " + entry.getKey(), Status.BAD_REQUEST);
170           }
171         }
172
173       }
174
175       Map<String, JsonElement> entriesMap = new HashMap<String, JsonElement>();
176       for (Map.Entry<String, JsonElement> entry : payloadEntriesSet) {
177         entriesMap.put(entry.getKey(), entry.getValue());
178       }
179
180       Vertex.Builder modelVertexBuilder = new Vertex.Builder(type);
181       if (id != null) {
182         modelVertexBuilder.id(id);
183       }
184       for (DatabaseMapping mapping : modelObjectType.getDescriptor().getMappings()) {
185         if (mapping.isAbstractDirectMapping()) {
186           DatabaseField field = mapping.getField();
187           String defaultValue = mapping.getProperties().get("defaultValue") == null ? ""
188               : mapping.getProperties().get("defaultValue").toString();
189
190           String keyName = field.getName().substring(0, field.getName().indexOf("/"));
191
192           if (((XMLField) field).isRequired() && !entriesMap.containsKey(keyName) && !defaultValue.isEmpty()) {
193             modelVertexBuilder.property(keyName, CrudServiceUtil.validateFieldType(defaultValue, field.getType()));
194           }
195           // if schema field is required and not set then reject
196           if (((XMLField) field).isRequired() && !entriesMap.containsKey(keyName) && defaultValue.isEmpty()) {
197             throw new CrudException("Missing required field: " + keyName, Status.BAD_REQUEST);
198           }
199           // If invalid field then reject
200           if (entriesMap.containsKey(keyName)) {
201             Object value = CrudServiceUtil.validateFieldType(entriesMap.get(keyName).getAsString(), field.getType());
202             modelVertexBuilder.property(keyName, value);
203           }
204
205           // Set defaults
206           if (!defaultValue.isEmpty() && !entriesMap.containsKey(keyName)) {
207             modelVertexBuilder.property(keyName, CrudServiceUtil.validateFieldType(defaultValue, field.getType()));
208           }
209         }
210       }
211
212       // Handle reserved properties
213       for (DatabaseMapping mapping : reservedType.getDescriptor().getMappings()) {
214         if (mapping.isAbstractDirectMapping()) {
215           DatabaseField field = mapping.getField();
216           String keyName = field.getName().substring(0, field.getName().indexOf("/"));
217
218           if (entriesMap.containsKey(keyName)) {
219             Object value = CrudServiceUtil.validateFieldType(entriesMap.get(keyName).getAsString(), field.getType());
220             modelVertexBuilder.property(keyName, value);
221           }
222         }
223       }
224
225       return modelVertexBuilder.build();
226     } catch (Exception e) {
227       throw new CrudException(e.getMessage(), Status.BAD_REQUEST);
228     }
229   }
230
231   public static Vertex validateIncomingPatchPayload(String id, String version, String type, JsonElement properties,
232       Vertex existingVertex) throws CrudException {
233     try {
234       type = resolveCollectionType(version, type);
235       DynamicJAXBContext jaxbContext = OxmModelLoader.getContextForVersion(version);
236       String modelObjectClass = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL,
237           CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, type));
238
239       final DynamicType modelObjectType = jaxbContext.getDynamicType(modelObjectClass);
240       final DynamicType reservedType = jaxbContext.getDynamicType("ReservedPropNames");
241
242       Set<Map.Entry<String, JsonElement>> payloadEntriesSet = properties.getAsJsonObject().entrySet();
243
244       // Loop through the payload properties and merge with existing
245       // vertex props
246       for (Map.Entry<String, JsonElement> entry : payloadEntriesSet) {
247
248         String keyJavaName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, entry.getKey());
249
250         DatabaseField field = null;
251         String defaultValue = null;
252
253         if (modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName) != null) {
254           field = modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName).getField();
255           defaultValue = modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName).getProperties()
256               .get("defaultValue") == null ? ""
257                   : modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName).getProperties()
258                       .get("defaultValue").toString();
259         } else if (reservedType.getDescriptor().getMappingForAttributeName(keyJavaName) != null) {
260           field = reservedType.getDescriptor().getMappingForAttributeName(keyJavaName).getField();
261           defaultValue = "";
262         }
263
264         if (field == null) {
265           throw new CrudException("Invalid field: " + entry.getKey(), Status.BAD_REQUEST);
266         }
267
268         // check if mandatory field is not set to null
269         if (((XMLField) field).isRequired() && entry.getValue() instanceof JsonNull && !defaultValue.isEmpty()) {
270           existingVertex.getProperties().put(entry.getKey(),
271               CrudServiceUtil.validateFieldType(defaultValue, field.getType()));
272         } else if (((XMLField) field).isRequired() && entry.getValue() instanceof JsonNull && defaultValue.isEmpty()) {
273           throw new CrudException("Mandatory field: " + entry.getKey() + " can't be set to null", Status.BAD_REQUEST);
274         } else if (!((XMLField) field).isRequired() && entry.getValue() instanceof JsonNull
275             && existingVertex.getProperties().containsKey(entry.getKey())) {
276           existingVertex.getProperties().remove(entry.getKey());
277         } else if (!(entry.getValue() instanceof JsonNull)) {
278           // add/update the value if found in existing vertex
279           Object value = CrudServiceUtil.validateFieldType(entry.getValue().getAsString(), field.getType());
280           existingVertex.getProperties().put(entry.getKey(), value);
281         }
282       }
283
284       return existingVertex;
285     } catch (Exception e) {
286       throw new CrudException(e.getMessage(), Status.BAD_REQUEST);
287     }
288   }
289
290   private static DatabaseField getDatabaseField(String fieldName, DynamicType modelObjectType) {
291     for (DatabaseField field : modelObjectType.getDescriptor().getAllFields()) {
292       int ix = field.getName().indexOf("/");
293       if (ix <= 0) {
294         ix = field.getName().length();
295       }
296
297       String keyName = field.getName().substring(0, ix);
298       if (fieldName.equals(keyName)) {
299         return field;
300       }
301     }
302     return null;
303   }
304
305   public static Vertex validateOutgoingPayload(String version, Vertex vertex) { 
306     Vertex.Builder modelVertexBuilder = new Vertex.Builder(vertex.getType()).id(vertex.getId().get());
307
308     try {
309       DynamicJAXBContext jaxbContext = OxmModelLoader.getContextForVersion(version);
310       String modelObjectClass = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL,
311           CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL,
312               vertex.getProperties().get(Metadata.NODE_TYPE.propertyName()) != null
313                   ? vertex.getProperties().get(Metadata.NODE_TYPE.propertyName()).toString() : vertex.getType()));
314       final DynamicType modelObjectType = jaxbContext.getDynamicType(modelObjectClass);
315
316       for (String key : vertex.getProperties().keySet()) {
317         DatabaseField field = getDatabaseField(key, modelObjectType);
318         if (field != null) {
319           if (!Metadata.isProperty(key)) {
320             modelVertexBuilder.property(key, vertex.getProperties().get(key));
321           }
322         }
323       }
324       
325       return modelVertexBuilder.build();
326     } catch (Exception ex) {
327       return vertex;
328     }
329
330   }
331
332 }