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