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.validation;
23 import java.util.HashMap;
26 import javax.ws.rs.core.Response.Status;
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.aai.cl.api.Logger;
33 import org.onap.aai.cl.eelf.LoggerFactory;
34 import org.onap.crud.entity.Vertex;
35 import org.onap.crud.exception.CrudException;
36 import org.onap.crud.logging.CrudServiceMsgs;
37 import org.onap.crud.util.CrudServiceConstants;
38 import org.onap.crud.util.CrudServiceUtil;
39 import org.onap.schema.OxmModelLoader;
40 import com.google.common.base.CaseFormat;
41 import com.google.gson.JsonElement;
42 import com.google.gson.JsonNull;
44 public class OxmModelValidator {
45 private static Logger logger = LoggerFactory.getInstance().getLogger(OxmModelValidator.class.getName());
47 public enum Metadata {
48 NODE_TYPE("aai-node-type"),
50 CREATED_TS("aai-created-ts"),
51 UPDATED_TS("aai-last-mod-ts"),
52 SOT("source-of-truth"),
53 LAST_MOD_SOT("last-mod-source-of-truth");
55 private final String propName;
57 Metadata(String propName) {
58 this.propName = propName;
61 public String propertyName() {
65 public static boolean isProperty(String property) {
66 for (Metadata meta : Metadata.values()) {
67 if (meta.propName.equals(property)) {
75 public static Map<String, Object> resolveCollectionfilter(String version, String type, Map<String, String> filter)
76 throws CrudException {
78 DynamicJAXBContext jaxbContext = null;
80 jaxbContext = OxmModelLoader.getContextForVersion(version);
81 } catch (Exception e) {
82 throw new CrudException(e);
85 Map<String, Object> result = new HashMap<String, Object>();
86 if (jaxbContext == null) {
87 logger.error(CrudServiceMsgs.OXM_LOAD_ERROR, "Error loading oxm model: " + version);
88 throw new CrudException("Error loading oxm model: " + version, Status.NOT_FOUND);
90 final DynamicType modelObjectType = jaxbContext.getDynamicType(
91 CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, type)));
92 final DynamicType reservedObjectType = jaxbContext.getDynamicType("ReservedPropNames");
94 for (String key : filter.keySet()) {
95 if ((key == CrudServiceConstants.CRD_RESERVED_VERSION ) || key == CrudServiceConstants.CRD_RESERVED_NODE_TYPE ) {
96 result.put ( key, filter.get ( key ) );
99 String keyJavaName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, key);
100 DatabaseMapping mapping = modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName);
102 // Try both the model for the specified type and the reserved properties for our key
103 if (mapping == null) {
104 mapping = reservedObjectType.getDescriptor().getMappingForAttributeName(keyJavaName);
106 if (mapping != null) {
108 Object value = CrudServiceUtil.validateFieldType(filter.get(key), mapping.getField().getType());
109 result.put(key, value);
110 } catch (Exception ex) {
111 // Skip any exceptions thrown while validating the filter
122 public static String resolveCollectionType(String version, String type) throws CrudException {
124 DynamicJAXBContext jaxbContext = null;
126 jaxbContext = OxmModelLoader.getContextForVersion(version);
127 } catch (CrudException ce) {
128 throw new CrudException(ce.getMessage(), ce.getHttpStatus());
129 } catch (Exception e) {
130 throw new CrudException(e);
133 if (jaxbContext == null) {
134 logger.error(CrudServiceMsgs.OXM_LOAD_ERROR, "Error loading oxm model: " + version);
135 throw new CrudException("Error loading oxm model: " + version, Status.NOT_FOUND);
137 // Determine if the Object part is a collection type in the model
139 final DynamicType modelObjectType = jaxbContext.getDynamicType(
140 CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, type)));
142 if (modelObjectType == null) {
143 logger.error(CrudServiceMsgs.INVALID_OXM_FILE, "Object of collection type not found: " + type);
144 throw new CrudException("Object of collection type not found: " + type, Status.NOT_FOUND);
147 if (modelObjectType.getDescriptor().getMappings().size() == 1
148 && modelObjectType.getDescriptor().getMappings().get(0).isCollectionMapping()) {
149 String childJavaObjectName = modelObjectType.getDescriptor().getMappings().get(0).getAttributeName();
150 childJavaObjectName = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, childJavaObjectName);
151 final DynamicType childObjectType = jaxbContext.getDynamicType(childJavaObjectName);
152 if (childObjectType == null) {
153 // Should not happen as child object is defined in oxm model itself
154 logger.error(CrudServiceMsgs.INVALID_OXM_FILE, "Child Object Type for Java Object not found: " + childJavaObjectName);
155 throw new CrudException("Child Object Type for Java Object not found: " + childJavaObjectName, Status.NOT_FOUND);
157 return childObjectType.getDescriptor().getTableName();
159 return modelObjectType.getDescriptor().getTableName();
164 public static Vertex validateIncomingUpsertPayload(String id, String version, String type, JsonElement properties)
165 throws CrudException {
168 type = resolveCollectionType(version, type);
169 DynamicJAXBContext jaxbContext = OxmModelLoader.getContextForVersion(version);
170 String modelObjectClass = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL,
171 CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, type));
173 final DynamicType modelObjectType = jaxbContext.getDynamicType(modelObjectClass);
174 final DynamicType reservedType = jaxbContext.getDynamicType("ReservedPropNames");
176 Set<Map.Entry<String, JsonElement>> payloadEntriesSet = properties.getAsJsonObject().entrySet();
178 // loop through input to validate against schema
179 for (Map.Entry<String, JsonElement> entry : payloadEntriesSet) {
180 String keyJavaName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, entry.getKey());
182 // check for valid field
183 if (modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName) == null) {
184 if (reservedType.getDescriptor().getMappingForAttributeName(keyJavaName) == null) {
185 throw new CrudException("Invalid field: " + entry.getKey(), Status.BAD_REQUEST);
191 Map<String, JsonElement> entriesMap = new HashMap<String, JsonElement>();
192 for (Map.Entry<String, JsonElement> entry : payloadEntriesSet) {
193 entriesMap.put(entry.getKey(), entry.getValue());
196 Vertex.Builder modelVertexBuilder = new Vertex.Builder(type);
198 modelVertexBuilder.id(id);
200 for (DatabaseMapping mapping : modelObjectType.getDescriptor().getMappings()) {
201 if (mapping.isAbstractDirectMapping()) {
202 DatabaseField field = mapping.getField();
203 String defaultValue = mapping.getProperties().get("defaultValue") == null ? ""
204 : mapping.getProperties().get("defaultValue").toString();
206 String keyName = field.getName().substring(0, field.getName().indexOf("/"));
208 if (((XMLField) field).isRequired() && !entriesMap.containsKey(keyName) && !defaultValue.isEmpty()) {
209 modelVertexBuilder.property(keyName, CrudServiceUtil.validateFieldType(defaultValue, field.getType()));
211 // if schema field is required and not set then reject
212 if (((XMLField) field).isRequired() && !entriesMap.containsKey(keyName) && defaultValue.isEmpty()) {
213 throw new CrudException("Missing required field: " + keyName, Status.BAD_REQUEST);
215 // If invalid field then reject
216 if (entriesMap.containsKey(keyName)) {
217 Object value = CrudServiceUtil.validateFieldType(entriesMap.get(keyName).getAsString(), field.getType());
218 modelVertexBuilder.property(keyName, value);
222 if (!defaultValue.isEmpty() && !entriesMap.containsKey(keyName)) {
223 modelVertexBuilder.property(keyName, CrudServiceUtil.validateFieldType(defaultValue, field.getType()));
228 // Handle reserved properties
229 for (DatabaseMapping mapping : reservedType.getDescriptor().getMappings()) {
230 if (mapping.isAbstractDirectMapping()) {
231 DatabaseField field = mapping.getField();
232 String keyName = field.getName().substring(0, field.getName().indexOf("/"));
234 if (entriesMap.containsKey(keyName)) {
235 Object value = CrudServiceUtil.validateFieldType(entriesMap.get(keyName).getAsString(), field.getType());
236 modelVertexBuilder.property(keyName, value);
241 return modelVertexBuilder.build();
242 } catch (CrudException ce) {
243 throw new CrudException(ce.getMessage(), ce.getHttpStatus());
244 } catch (Exception e) {
245 throw new CrudException(e.getMessage(), Status.BAD_REQUEST);
249 public static Vertex validateIncomingPatchPayload(String id, String version, String type, JsonElement properties,
250 Vertex existingVertex) throws CrudException {
252 type = resolveCollectionType(version, type);
253 DynamicJAXBContext jaxbContext = OxmModelLoader.getContextForVersion(version);
254 String modelObjectClass = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL,
255 CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, type));
257 final DynamicType modelObjectType = jaxbContext.getDynamicType(modelObjectClass);
258 final DynamicType reservedType = jaxbContext.getDynamicType("ReservedPropNames");
260 Set<Map.Entry<String, JsonElement>> payloadEntriesSet = properties.getAsJsonObject().entrySet();
262 // Loop through the payload properties and merge with existing
264 for (Map.Entry<String, JsonElement> entry : payloadEntriesSet) {
266 String keyJavaName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, entry.getKey());
268 DatabaseField field = null;
269 String defaultValue = null;
271 if (modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName) != null) {
272 field = modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName).getField();
273 defaultValue = modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName).getProperties()
274 .get("defaultValue") == null ? ""
275 : modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName).getProperties()
276 .get("defaultValue").toString();
277 } else if (reservedType.getDescriptor().getMappingForAttributeName(keyJavaName) != null) {
278 field = reservedType.getDescriptor().getMappingForAttributeName(keyJavaName).getField();
283 throw new CrudException("Invalid field: " + entry.getKey(), Status.BAD_REQUEST);
286 // check if mandatory field is not set to null
287 if (((XMLField) field).isRequired() && entry.getValue() instanceof JsonNull && !defaultValue.isEmpty()) {
288 existingVertex.getProperties().put(entry.getKey(),
289 CrudServiceUtil.validateFieldType(defaultValue, field.getType()));
290 } else if (((XMLField) field).isRequired() && entry.getValue() instanceof JsonNull && defaultValue.isEmpty()) {
291 throw new CrudException("Mandatory field: " + entry.getKey() + " can't be set to null", Status.BAD_REQUEST);
292 } else if (!((XMLField) field).isRequired() && entry.getValue() instanceof JsonNull
293 && existingVertex.getProperties().containsKey(entry.getKey())) {
294 existingVertex.getProperties().remove(entry.getKey());
295 } else if (!(entry.getValue() instanceof JsonNull)) {
296 // add/update the value if found in existing vertex
297 Object value = CrudServiceUtil.validateFieldType(entry.getValue().getAsString(), field.getType());
298 existingVertex.getProperties().put(entry.getKey(), value);
302 return existingVertex;
303 } catch (Exception e) {
304 throw new CrudException(e.getMessage(), Status.BAD_REQUEST);
308 private static DatabaseField getDatabaseField(String fieldName, DynamicType modelObjectType) {
309 for (DatabaseField field : modelObjectType.getDescriptor().getAllFields()) {
310 int ix = field.getName().indexOf("/");
312 ix = field.getName().length();
315 String keyName = field.getName().substring(0, ix);
316 if (fieldName.equals(keyName)) {
323 public static Vertex validateOutgoingPayload(String version, Vertex vertex) {
324 Vertex.Builder modelVertexBuilder = new Vertex.Builder(vertex.getType()).id(vertex.getId().get());
327 DynamicJAXBContext jaxbContext = OxmModelLoader.getContextForVersion(version);
328 String modelObjectClass = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL,
329 CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL,
330 vertex.getProperties().get(Metadata.NODE_TYPE.propertyName()) != null
331 ? vertex.getProperties().get(Metadata.NODE_TYPE.propertyName()).toString() : vertex.getType()));
332 final DynamicType modelObjectType = jaxbContext.getDynamicType(modelObjectClass);
333 final DynamicType reservedObjectType = jaxbContext.getDynamicType("ReservedPropNames");
335 for (String key : vertex.getProperties().keySet()) {
336 DatabaseField field = getDatabaseField(key, modelObjectType);
338 field = getDatabaseField(key, reservedObjectType);
341 modelVertexBuilder.property(key, vertex.getProperties().get(key));
345 return modelVertexBuilder.build();
346 } catch (Exception ex) {