0ae3e134f3882860ad1fc6a481abbd0e76e28618
[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
167       Set<Map.Entry<String, JsonElement>> payloadEntriesSet = properties.getAsJsonObject()
168           .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           throw new CrudException("Invalid field: " + entry.getKey(), Status.BAD_REQUEST);
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)
199               && !defaultValue.isEmpty()) {
200             modelVertexBuilder.property(keyName,
201                 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)
205               && defaultValue.isEmpty()) {
206             throw new CrudException("Missing required field: " + keyName, Status.BAD_REQUEST);
207           }
208           // If invalid field then reject
209           if (entriesMap.containsKey(keyName)) {
210             Object value = CrudServiceUtil.validateFieldType(entriesMap.get(keyName)
211                 .getAsString(), field.getType());
212             modelVertexBuilder.property(keyName, value);
213           }
214
215           // Set defaults
216           if (!defaultValue.isEmpty() && !entriesMap.containsKey(keyName)) {
217             modelVertexBuilder.property(keyName,
218                 CrudServiceUtil.validateFieldType(defaultValue, field.getType()));
219           }
220         }
221       }
222
223       return modelVertexBuilder.build();
224     } catch (Exception e) {
225       throw new CrudException(e.getMessage(), Status.BAD_REQUEST);
226     }
227   }
228
229   public static Vertex validateIncomingPatchPayload(String id, String version, String type,
230                                                     JsonElement properties, Vertex existingVertex)
231       throws CrudException {
232
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
241       Set<Map.Entry<String, JsonElement>> payloadEntriesSet = properties.getAsJsonObject()
242           .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         // check for valid field
251         if (modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName) == null) {
252           throw new CrudException("Invalid field: " + entry.getKey(), Status.BAD_REQUEST);
253         }
254
255         DatabaseField field = modelObjectType.getDescriptor()
256             .getMappingForAttributeName(keyJavaName).getField();
257         String defaultValue = modelObjectType.getDescriptor()
258             .getMappingForAttributeName(keyJavaName)
259             .getProperties().get("defaultValue") == null ? ""
260             : modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName)
261             .getProperties().get("defaultValue").toString();
262
263         // check if mandatory field is not set to null
264         if (((XMLField) field).isRequired() && entry.getValue() instanceof JsonNull
265             && !defaultValue.isEmpty()) {
266           existingVertex.getProperties().put(entry.getKey(),
267               CrudServiceUtil.validateFieldType(defaultValue, field.getType()));
268         } else if (((XMLField) field).isRequired() && entry.getValue() instanceof JsonNull
269             && defaultValue.isEmpty()) {
270           throw new CrudException("Mandatory field: " + entry.getKey()
271               + " can't be set to null",
272               Status.BAD_REQUEST);
273         } else if (!((XMLField) field).isRequired() && entry.getValue() instanceof JsonNull
274             && existingVertex.getProperties().containsKey(entry.getKey())) {
275           existingVertex.getProperties().remove(entry.getKey());
276         } else if (!(entry.getValue() instanceof JsonNull)) {
277           // add/update the value if found in existing vertex
278           Object value = CrudServiceUtil.validateFieldType(entry.getValue().getAsString(),
279               field.getType());
280           existingVertex.getProperties().put(entry.getKey(), value);
281         }
282
283       }
284
285       return existingVertex;
286     } catch (Exception e) {
287       throw new CrudException(e.getMessage(), Status.BAD_REQUEST);
288     }
289
290   }
291
292   private static DatabaseField getDatabaseField(String fieldName, DynamicType modelObjectType) {
293     for (DatabaseField field : modelObjectType.getDescriptor().getAllFields()) {
294       int ix = field.getName().indexOf("/");
295       if (ix <= 0) {
296         ix = field.getName().length();
297       }
298
299       String keyName = field.getName().substring(0, ix);
300       if (fieldName.equals(keyName)) {
301         return field;
302       }
303     }
304     return null;
305   }
306
307   public static Vertex validateOutgoingPayload(String version, Vertex vertex) {
308
309     Vertex.Builder modelVertexBuilder = new Vertex.Builder(vertex.getType())
310         .id(vertex.getId().get());
311
312     try {
313       DynamicJAXBContext jaxbContext = OxmModelLoader.getContextForVersion(version);
314       String modelObjectClass = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL,
315           CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL,
316               vertex.getProperties().get(Metadata.NODE_TYPE.propertyName()) != null
317                   ? vertex.getProperties().get(Metadata.NODE_TYPE.propertyName()).toString() : vertex.getType()));
318       final DynamicType modelObjectType = jaxbContext.getDynamicType(modelObjectClass);
319
320       for (String key : vertex.getProperties().keySet()) {
321         DatabaseField field = getDatabaseField(key, modelObjectType);
322         if (field != null) {
323           if (!Metadata.isProperty(key)) {
324             modelVertexBuilder.property(key, vertex.getProperties().get(key));
325           }
326         }
327       }
328       return modelVertexBuilder.build();
329     } catch (Exception ex) {
330       return vertex;
331     }
332
333   }
334
335
336 }