Add bulk API to gizmo
[aai/gizmo.git] / src / main / java / org / openecomp / 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.openecomp.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.openecomp.crud.entity.Vertex;
37 import org.openecomp.crud.exception.CrudException;
38 import org.openecomp.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     SOT("source-of-truth"),
51     LAST_MOD_SOT("last-mod-source-of-truth");
52
53     private final String propName;
54
55     Metadata(String propName) {
56       this.propName = propName;
57     }
58
59     public String propertyName() {
60       return propName;
61     }
62
63     public static boolean isProperty(String property) {
64       for (Metadata meta : Metadata.values()) {
65         if (meta.propName.equals(property)) {
66           return true;
67         }
68       }
69       return false;
70     }
71   }
72
73
74   public static Map<String, Object> resolveCollectionfilter(String version, String type,
75                                                             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       throw new CrudException("", Status.NOT_FOUND);
88     }
89     final DynamicType modelObjectType = jaxbContext.getDynamicType(CaseFormat.LOWER_CAMEL
90         .to(CaseFormat.UPPER_CAMEL,
91         CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, type)));
92
93     for (String key : filter.keySet()) {
94       String keyJavaName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, key);
95       if (modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName) != null) {
96         try {
97           DatabaseMapping mapping = modelObjectType.getDescriptor()
98               .getMappingForAttributeName(keyJavaName);
99           Object value = CrudServiceUtil.validateFieldType(filter.get(key),
100               mapping.getField().getType());
101           result.put(key, value);
102         } catch (Exception ex) {
103           // Skip any exceptions thrown while validating the filter
104           // key value
105           continue;
106         }
107       }
108     }
109
110     return result;
111
112   }
113
114   public static String resolveCollectionType(String version, String type) throws CrudException {
115
116     DynamicJAXBContext jaxbContext = null;
117     try {
118       jaxbContext = OxmModelLoader.getContextForVersion(version);
119     } catch (Exception e) {
120       throw new CrudException(e);
121     }
122
123     if (jaxbContext == null) {
124       throw new CrudException("", Status.NOT_FOUND);
125     }
126     // Determine if the Object part is a collection type in the model
127     // definition
128     final DynamicType modelObjectType = jaxbContext.getDynamicType(CaseFormat.LOWER_CAMEL
129         .to(CaseFormat.UPPER_CAMEL,
130         CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, type)));
131
132     if (modelObjectType == null) {
133       throw new CrudException("", Status.NOT_FOUND);
134     }
135
136     if (modelObjectType.getDescriptor().getMappings().size() == 1
137         && modelObjectType.getDescriptor().getMappings().get(0).isCollectionMapping()) {
138       String childJavaObjectName = modelObjectType.getDescriptor().getMappings()
139           .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
155   public static Vertex validateIncomingUpsertPayload(String id, String version, String type,
156                                                      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()
169           .entrySet();
170
171       //loop through input to validate against schema
172       for (Map.Entry<String, JsonElement> entry : payloadEntriesSet) {
173         String keyJavaName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, entry.getKey());
174
175         // check for valid field
176         if (modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName) == null) {
177                 if(reservedType.getDescriptor().getMappingForAttributeName(keyJavaName) == null){
178                         throw new CrudException("Invalid field: " + entry.getKey(), Status.BAD_REQUEST);
179                 }
180         }
181
182       }
183
184       Map<String, JsonElement> entriesMap = new HashMap<String, JsonElement>();
185       for (Map.Entry<String, JsonElement> entry : payloadEntriesSet) {
186         entriesMap.put(entry.getKey(), entry.getValue());
187       }
188
189       Vertex.Builder modelVertexBuilder = new Vertex.Builder(type);
190       if (id != null) {
191         modelVertexBuilder.id(id);
192       }
193       for (DatabaseMapping mapping : modelObjectType.getDescriptor().getMappings()) {
194         if (mapping.isAbstractDirectMapping()) {
195           DatabaseField field = mapping.getField();
196           String defaultValue = mapping.getProperties().get("defaultValue") == null ? ""
197               : mapping.getProperties().get("defaultValue").toString();
198
199           String keyName = field.getName().substring(0, field.getName().indexOf("/"));
200
201           if (((XMLField) field).isRequired() && !entriesMap.containsKey(keyName)
202               && !defaultValue.isEmpty()) {
203             modelVertexBuilder.property(keyName,
204                 CrudServiceUtil.validateFieldType(defaultValue, field.getType()));
205           }
206           // if schema field is required and not set then reject
207           if (((XMLField) field).isRequired() && !entriesMap.containsKey(keyName)
208               && defaultValue.isEmpty()) {
209             throw new CrudException("Missing required field: " + keyName, Status.BAD_REQUEST);
210           }
211           // If invalid field then reject
212           if (entriesMap.containsKey(keyName)) {
213             Object value = CrudServiceUtil.validateFieldType(entriesMap.get(keyName)
214                 .getAsString(), field.getType());
215             modelVertexBuilder.property(keyName, value);
216           }
217
218           // Set defaults
219           if (!defaultValue.isEmpty() && !entriesMap.containsKey(keyName)) {
220             modelVertexBuilder.property(keyName,
221                 CrudServiceUtil.validateFieldType(defaultValue, field.getType()));
222           }
223         }
224       }
225       
226       // Handle reserved properties
227       for (DatabaseMapping mapping : reservedType.getDescriptor().getMappings()) {
228         if (mapping.isAbstractDirectMapping()) {
229           DatabaseField field = mapping.getField();
230           String keyName = field.getName().substring(0, field.getName().indexOf("/"));
231
232           if (entriesMap.containsKey(keyName)) {
233             Object value = CrudServiceUtil.validateFieldType(entriesMap.get(keyName)
234                 .getAsString(), field.getType());
235             modelVertexBuilder.property(keyName, value);
236           }
237         }
238       }
239
240       return modelVertexBuilder.build();
241     } catch (Exception e) {
242       throw new CrudException(e.getMessage(), Status.BAD_REQUEST);
243     }
244   }
245
246   public static Vertex validateIncomingPatchPayload(String id, String version, String type,
247                                                     JsonElement properties, Vertex existingVertex)
248       throws CrudException {
249
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()
260           .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()
274               .getMappingForAttributeName(keyJavaName)
275               .getProperties().get("defaultValue") == null ? ""
276               : modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName)
277               .getProperties().get("defaultValue").toString();
278         }
279         else if (reservedType.getDescriptor().getMappingForAttributeName(keyJavaName) != null) {
280           field = reservedType.getDescriptor().getMappingForAttributeName(keyJavaName).getField();
281           defaultValue = "";
282         }
283         
284         if (field == null) {
285           throw new CrudException("Invalid field: " + entry.getKey(), Status.BAD_REQUEST);
286         }
287
288         // check if mandatory field is not set to null
289         if (((XMLField) field).isRequired() && entry.getValue() instanceof JsonNull
290             && !defaultValue.isEmpty()) {
291           existingVertex.getProperties().put(entry.getKey(),
292               CrudServiceUtil.validateFieldType(defaultValue, field.getType()));
293         } else if (((XMLField) field).isRequired() && entry.getValue() instanceof JsonNull
294             && defaultValue.isEmpty()) {
295           throw new CrudException("Mandatory field: " + entry.getKey()
296               + " can't be set to null",
297               Status.BAD_REQUEST);
298         } else if (!((XMLField) field).isRequired() && entry.getValue() instanceof JsonNull
299             && existingVertex.getProperties().containsKey(entry.getKey())) {
300           existingVertex.getProperties().remove(entry.getKey());
301         } else if (!(entry.getValue() instanceof JsonNull)) {
302           // add/update the value if found in existing vertex
303           Object value = CrudServiceUtil.validateFieldType(entry.getValue().getAsString(),
304               field.getType());
305           existingVertex.getProperties().put(entry.getKey(), value);
306         }
307
308       }
309
310       return existingVertex;
311     } catch (Exception e) {
312       throw new CrudException(e.getMessage(), Status.BAD_REQUEST);
313     }
314
315   }
316   
317   private static DatabaseField getDatabaseField(String fieldName, DynamicType modelObjectType) {
318     for (DatabaseField field : modelObjectType.getDescriptor().getAllFields()) {
319       int ix = field.getName().indexOf("/");
320       if (ix <= 0) {
321         ix = field.getName().length();
322       }
323
324       String keyName = field.getName().substring(0, ix);
325       if (fieldName.equals(keyName)) {
326         return field;
327       }
328     }
329     return null;
330   }
331
332   public static Vertex validateOutgoingPayload(String version, Vertex vertex) {
333
334     Vertex.Builder modelVertexBuilder = new Vertex.Builder(vertex.getType())
335         .id(vertex.getId().get());
336
337     try {
338       DynamicJAXBContext jaxbContext = OxmModelLoader.getContextForVersion(version);
339       String modelObjectClass = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL,
340           CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL,
341               vertex.getProperties().get(Metadata.NODE_TYPE.propertyName()) != null
342                   ? vertex.getProperties().get(Metadata.NODE_TYPE.propertyName()).toString() : vertex.getType()));
343       final DynamicType modelObjectType = jaxbContext.getDynamicType(modelObjectClass);
344
345       for (String key : vertex.getProperties().keySet()) {
346         DatabaseField field = getDatabaseField(key, modelObjectType);
347         if (field != null) {
348           if (!Metadata.isProperty(key)) {
349             modelVertexBuilder.property(key, vertex.getProperties().get(key));
350           }
351         }
352       }
353       return modelVertexBuilder.build();
354     } catch (Exception ex) {
355       return vertex;
356     }
357
358   }
359
360
361 }