2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
6 * Copyright © 2017-2018 Amdocs
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END=========================================================
21 package org.onap.schema;
23 import com.google.common.base.CaseFormat;
24 import com.google.gson.JsonElement;
25 import com.google.gson.JsonNull;
27 import org.eclipse.persistence.dynamic.DynamicType;
28 import org.eclipse.persistence.internal.helper.DatabaseField;
29 import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext;
30 import org.eclipse.persistence.mappings.DatabaseMapping;
31 import org.eclipse.persistence.oxm.XMLField;
32 import org.onap.aaiutils.oxm.OxmModelLoader;
33 import org.onap.crud.entity.Vertex;
34 import org.onap.crud.exception.CrudException;
35 import org.onap.crud.util.CrudServiceUtil;
37 import java.util.HashMap;
40 import javax.ws.rs.core.Response.Status;
42 public class OxmModelValidator {
43 public enum Metadata {
44 NODE_TYPE("aai-node-type"),
46 CREATED_TS("aai-created-ts"),
47 UPDATED_TS("aai-last-mod-ts"),
48 SOT("source-of-truth"),
49 LAST_MOD_SOT("last-mod-source-of-truth");
51 private final String propName;
53 Metadata(String propName) {
54 this.propName = propName;
57 public String propertyName() {
61 public static boolean isProperty(String property) {
62 for (Metadata meta : Metadata.values()) {
63 if (meta.propName.equals(property)) {
71 public static Map<String, Object> resolveCollectionfilter(String version, String type, Map<String, String> filter)
72 throws CrudException {
74 DynamicJAXBContext jaxbContext = null;
76 jaxbContext = OxmModelLoader.getContextForVersion(version);
77 } catch (Exception e) {
78 throw new CrudException(e);
81 Map<String, Object> result = new HashMap<String, Object>();
82 if (jaxbContext == null) {
83 throw new CrudException("", Status.NOT_FOUND);
85 final DynamicType modelObjectType = jaxbContext.getDynamicType(
86 CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, type)));
87 final DynamicType reservedObjectType = jaxbContext.getDynamicType("ReservedPropNames");
89 for (String key : filter.keySet()) {
90 String keyJavaName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, key);
91 DatabaseMapping mapping = modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName);
93 // Try both the model for the specified type and the reserved properties for our key
94 if (mapping == null) {
95 mapping = reservedObjectType.getDescriptor().getMappingForAttributeName(keyJavaName);
97 if (mapping != null) {
99 Object value = CrudServiceUtil.validateFieldType(filter.get(key), mapping.getField().getType());
100 result.put(key, value);
101 } catch (Exception ex) {
102 // Skip any exceptions thrown while validating the filter
113 public static String resolveCollectionType(String version, String type) throws CrudException {
115 DynamicJAXBContext jaxbContext = null;
117 jaxbContext = OxmModelLoader.getContextForVersion(version);
118 } catch (Exception e) {
119 throw new CrudException(e);
122 if (jaxbContext == null) {
123 throw new CrudException("", Status.NOT_FOUND);
125 // Determine if the Object part is a collection type in the model
127 final DynamicType modelObjectType = jaxbContext.getDynamicType(
128 CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, type)));
130 if (modelObjectType == null) {
131 throw new CrudException("", Status.NOT_FOUND);
134 if (modelObjectType.getDescriptor().getMappings().size() == 1
135 && modelObjectType.getDescriptor().getMappings().get(0).isCollectionMapping()) {
136 String childJavaObjectName = modelObjectType.getDescriptor().getMappings().get(0).getAttributeName();
137 childJavaObjectName = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, childJavaObjectName);
138 final DynamicType childObjectType = jaxbContext.getDynamicType(childJavaObjectName);
139 if (childObjectType == null) {
140 // Should not happen as child object is defined in oxm model
142 throw new CrudException("", Status.NOT_FOUND);
144 return childObjectType.getDescriptor().getTableName();
146 return modelObjectType.getDescriptor().getTableName();
151 public static Vertex validateIncomingUpsertPayload(String id, String version, String type, JsonElement properties)
152 throws CrudException {
155 type = resolveCollectionType(version, type);
156 DynamicJAXBContext jaxbContext = OxmModelLoader.getContextForVersion(version);
157 String modelObjectClass = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL,
158 CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, type));
160 final DynamicType modelObjectType = jaxbContext.getDynamicType(modelObjectClass);
161 final DynamicType reservedType = jaxbContext.getDynamicType("ReservedPropNames");
163 Set<Map.Entry<String, JsonElement>> payloadEntriesSet = properties.getAsJsonObject().entrySet();
165 // loop through input to validate against schema
166 for (Map.Entry<String, JsonElement> entry : payloadEntriesSet) {
167 String keyJavaName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, entry.getKey());
169 // check for valid field
170 if (modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName) == null) {
171 if (reservedType.getDescriptor().getMappingForAttributeName(keyJavaName) == null) {
172 throw new CrudException("Invalid field: " + entry.getKey(), Status.BAD_REQUEST);
178 Map<String, JsonElement> entriesMap = new HashMap<String, JsonElement>();
179 for (Map.Entry<String, JsonElement> entry : payloadEntriesSet) {
180 entriesMap.put(entry.getKey(), entry.getValue());
183 Vertex.Builder modelVertexBuilder = new Vertex.Builder(type);
185 modelVertexBuilder.id(id);
187 for (DatabaseMapping mapping : modelObjectType.getDescriptor().getMappings()) {
188 if (mapping.isAbstractDirectMapping()) {
189 DatabaseField field = mapping.getField();
190 String defaultValue = mapping.getProperties().get("defaultValue") == null ? ""
191 : mapping.getProperties().get("defaultValue").toString();
193 String keyName = field.getName().substring(0, field.getName().indexOf("/"));
195 if (((XMLField) field).isRequired() && !entriesMap.containsKey(keyName) && !defaultValue.isEmpty()) {
196 modelVertexBuilder.property(keyName, CrudServiceUtil.validateFieldType(defaultValue, field.getType()));
198 // if schema field is required and not set then reject
199 if (((XMLField) field).isRequired() && !entriesMap.containsKey(keyName) && defaultValue.isEmpty()) {
200 throw new CrudException("Missing required field: " + keyName, Status.BAD_REQUEST);
202 // If invalid field then reject
203 if (entriesMap.containsKey(keyName)) {
204 Object value = CrudServiceUtil.validateFieldType(entriesMap.get(keyName).getAsString(), field.getType());
205 modelVertexBuilder.property(keyName, value);
209 if (!defaultValue.isEmpty() && !entriesMap.containsKey(keyName)) {
210 modelVertexBuilder.property(keyName, CrudServiceUtil.validateFieldType(defaultValue, field.getType()));
215 // Handle reserved properties
216 for (DatabaseMapping mapping : reservedType.getDescriptor().getMappings()) {
217 if (mapping.isAbstractDirectMapping()) {
218 DatabaseField field = mapping.getField();
219 String keyName = field.getName().substring(0, field.getName().indexOf("/"));
221 if (entriesMap.containsKey(keyName)) {
222 Object value = CrudServiceUtil.validateFieldType(entriesMap.get(keyName).getAsString(), field.getType());
223 modelVertexBuilder.property(keyName, value);
228 return modelVertexBuilder.build();
229 } catch (Exception e) {
230 throw new CrudException(e.getMessage(), Status.BAD_REQUEST);
234 public static Vertex validateIncomingPatchPayload(String id, String version, String type, JsonElement properties,
235 Vertex existingVertex) throws CrudException {
237 type = resolveCollectionType(version, type);
238 DynamicJAXBContext jaxbContext = OxmModelLoader.getContextForVersion(version);
239 String modelObjectClass = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL,
240 CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, type));
242 final DynamicType modelObjectType = jaxbContext.getDynamicType(modelObjectClass);
243 final DynamicType reservedType = jaxbContext.getDynamicType("ReservedPropNames");
245 Set<Map.Entry<String, JsonElement>> payloadEntriesSet = properties.getAsJsonObject().entrySet();
247 // Loop through the payload properties and merge with existing
249 for (Map.Entry<String, JsonElement> entry : payloadEntriesSet) {
251 String keyJavaName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, entry.getKey());
253 DatabaseField field = null;
254 String defaultValue = null;
256 if (modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName) != null) {
257 field = modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName).getField();
258 defaultValue = modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName).getProperties()
259 .get("defaultValue") == null ? ""
260 : modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName).getProperties()
261 .get("defaultValue").toString();
262 } else if (reservedType.getDescriptor().getMappingForAttributeName(keyJavaName) != null) {
263 field = reservedType.getDescriptor().getMappingForAttributeName(keyJavaName).getField();
268 throw new CrudException("Invalid field: " + entry.getKey(), Status.BAD_REQUEST);
271 // check if mandatory field is not set to null
272 if (((XMLField) field).isRequired() && entry.getValue() instanceof JsonNull && !defaultValue.isEmpty()) {
273 existingVertex.getProperties().put(entry.getKey(),
274 CrudServiceUtil.validateFieldType(defaultValue, field.getType()));
275 } else if (((XMLField) field).isRequired() && entry.getValue() instanceof JsonNull && defaultValue.isEmpty()) {
276 throw new CrudException("Mandatory field: " + entry.getKey() + " can't be set to null", Status.BAD_REQUEST);
277 } else if (!((XMLField) field).isRequired() && entry.getValue() instanceof JsonNull
278 && existingVertex.getProperties().containsKey(entry.getKey())) {
279 existingVertex.getProperties().remove(entry.getKey());
280 } else if (!(entry.getValue() instanceof JsonNull)) {
281 // add/update the value if found in existing vertex
282 Object value = CrudServiceUtil.validateFieldType(entry.getValue().getAsString(), field.getType());
283 existingVertex.getProperties().put(entry.getKey(), value);
287 return existingVertex;
288 } catch (Exception e) {
289 throw new CrudException(e.getMessage(), Status.BAD_REQUEST);
293 private static DatabaseField getDatabaseField(String fieldName, DynamicType modelObjectType) {
294 for (DatabaseField field : modelObjectType.getDescriptor().getAllFields()) {
295 int ix = field.getName().indexOf("/");
297 ix = field.getName().length();
300 String keyName = field.getName().substring(0, ix);
301 if (fieldName.equals(keyName)) {
308 public static Vertex validateOutgoingPayload(String version, Vertex vertex) {
309 Vertex.Builder modelVertexBuilder = new Vertex.Builder(vertex.getType()).id(vertex.getId().get());
312 DynamicJAXBContext jaxbContext = OxmModelLoader.getContextForVersion(version);
313 String modelObjectClass = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL,
314 CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL,
315 vertex.getProperties().get(Metadata.NODE_TYPE.propertyName()) != null
316 ? vertex.getProperties().get(Metadata.NODE_TYPE.propertyName()).toString() : vertex.getType()));
317 final DynamicType modelObjectType = jaxbContext.getDynamicType(modelObjectClass);
318 final DynamicType reservedObjectType = jaxbContext.getDynamicType("ReservedPropNames");
320 for (String key : vertex.getProperties().keySet()) {
321 DatabaseField field = getDatabaseField(key, modelObjectType);
323 field = getDatabaseField(key, reservedObjectType);
326 modelVertexBuilder.property(key, vertex.getProperties().get(key));
330 return modelVertexBuilder.build();
331 } catch (Exception ex) {