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());
46 private static final String OXM_LOAD_ERROR = "Error loading oxm model";
48 public enum Metadata {
49 NODE_TYPE("aai-node-type"),
51 CREATED_TS("aai-created-ts"),
52 UPDATED_TS("aai-last-mod-ts"),
53 SOT("source-of-truth"),
54 LAST_MOD_SOT("last-mod-source-of-truth");
56 private final String propName;
58 Metadata(String propName) {
59 this.propName = propName;
62 public String propertyName() {
66 public static boolean isProperty(String property) {
67 for (Metadata meta : Metadata.values()) {
68 if (meta.propName.equals(property)) {
76 public static Map<String, Object> resolveCollectionfilter(String version, String type, Map<String, String> filter)
77 throws CrudException {
79 DynamicJAXBContext jaxbContext = null;
81 jaxbContext = OxmModelLoader.getContextForVersion(version);
82 } catch (Exception e) {
83 throw new CrudException(e);
86 Map<String, Object> result = new HashMap<String, Object>();
87 if (jaxbContext == null) {
88 logger.error(CrudServiceMsgs.OXM_LOAD_ERROR, OXM_LOAD_ERROR + ": " + version);
89 throw new CrudException(OXM_LOAD_ERROR + ": " + version, Status.NOT_FOUND);
91 final DynamicType modelObjectType = OxmModelLoader.getDynamicTypeForVersion(version, 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, OXM_LOAD_ERROR + ": " + version);
135 throw new CrudException(OXM_LOAD_ERROR + ": " + version, Status.NOT_FOUND);
137 // Determine if the Object part is a collection type in the model
139 final DynamicType modelObjectType = OxmModelLoader.getDynamicTypeForVersion(version, type);
141 if (modelObjectType == null) {
142 logger.error(CrudServiceMsgs.INVALID_OXM_FILE, "Object of collection type not found: " + type);
143 throw new CrudException("Object of collection type not found: " + type, Status.NOT_FOUND);
146 if (modelObjectType.getDescriptor().getMappings().size() == 1
147 && modelObjectType.getDescriptor().getMappings().get(0).isCollectionMapping()) {
148 String childJavaObjectName = modelObjectType.getDescriptor().getMappings().get(0).getAttributeName();
149 childJavaObjectName = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, childJavaObjectName);
150 final DynamicType childObjectType = jaxbContext.getDynamicType(childJavaObjectName);
151 if (childObjectType == null) {
152 // Should not happen as child object is defined in oxm model itself
153 logger.error(CrudServiceMsgs.INVALID_OXM_FILE, "Child Object Type for Java Object not found: " + childJavaObjectName);
154 throw new CrudException("Child Object Type for Java Object not found: " + childJavaObjectName, Status.NOT_FOUND);
156 return childObjectType.getDescriptor().getTableName();
158 return modelObjectType.getDescriptor().getTableName();
163 public static Vertex validateIncomingUpsertPayload(String id, String version, String type, JsonElement properties)
164 throws CrudException {
167 type = resolveCollectionType(version, type);
168 DynamicJAXBContext jaxbContext = OxmModelLoader.getContextForVersion(version);
170 final DynamicType modelObjectType = OxmModelLoader.getDynamicTypeForVersion(version, type);
171 final DynamicType reservedType = jaxbContext.getDynamicType("ReservedPropNames");
173 Set<Map.Entry<String, JsonElement>> payloadEntriesSet = properties.getAsJsonObject().entrySet();
175 // loop through input to validate against schema
176 for (Map.Entry<String, JsonElement> entry : payloadEntriesSet) {
177 String keyJavaName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, entry.getKey());
179 // check for valid field
180 if (modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName) == null) {
181 if (reservedType.getDescriptor().getMappingForAttributeName(keyJavaName) == null) {
182 throw new CrudException("Invalid field: " + entry.getKey(), Status.BAD_REQUEST);
188 Map<String, JsonElement> entriesMap = new HashMap<String, JsonElement>();
189 for (Map.Entry<String, JsonElement> entry : payloadEntriesSet) {
190 entriesMap.put(entry.getKey(), entry.getValue());
193 Vertex.Builder modelVertexBuilder = new Vertex.Builder(type);
195 modelVertexBuilder.id(id);
197 for (DatabaseMapping mapping : modelObjectType.getDescriptor().getMappings()) {
198 if (mapping.isAbstractDirectMapping()) {
199 DatabaseField field = mapping.getField();
200 String defaultValue = mapping.getProperties().get("defaultValue") == null ? ""
201 : mapping.getProperties().get("defaultValue").toString();
203 String keyName = field.getName().substring(0, field.getName().indexOf("/"));
205 if (((XMLField) field).isRequired() && !entriesMap.containsKey(keyName) && !defaultValue.isEmpty()) {
206 modelVertexBuilder.property(keyName, CrudServiceUtil.validateFieldType(defaultValue, field.getType()));
208 // if schema field is required and not set then reject
209 if (((XMLField) field).isRequired() && !entriesMap.containsKey(keyName) && defaultValue.isEmpty()) {
210 throw new CrudException("Missing required field: " + keyName, Status.BAD_REQUEST);
212 // If invalid field then reject
213 if (entriesMap.containsKey(keyName)) {
214 Object value = CrudServiceUtil.validateFieldType(entriesMap.get(keyName).getAsString(), field.getType());
215 modelVertexBuilder.property(keyName, value);
219 if (!defaultValue.isEmpty() && !entriesMap.containsKey(keyName)) {
220 modelVertexBuilder.property(keyName, CrudServiceUtil.validateFieldType(defaultValue, field.getType()));
225 // Handle reserved properties
226 for (DatabaseMapping mapping : reservedType.getDescriptor().getMappings()) {
227 if (mapping.isAbstractDirectMapping()) {
228 DatabaseField field = mapping.getField();
229 String keyName = field.getName().substring(0, field.getName().indexOf("/"));
231 if (entriesMap.containsKey(keyName)) {
232 Object value = CrudServiceUtil.validateFieldType(entriesMap.get(keyName).getAsString(), field.getType());
233 modelVertexBuilder.property(keyName, value);
238 return modelVertexBuilder.build();
239 } catch (CrudException ce) {
240 throw new CrudException(ce.getMessage(), ce.getHttpStatus());
241 } catch (Exception e) {
242 throw new CrudException(e.getMessage(), Status.BAD_REQUEST);
246 public static Vertex validateIncomingPatchPayload(String id, String version, String type, JsonElement properties,
247 Vertex existingVertex) throws CrudException {
249 type = resolveCollectionType(version, type);
250 DynamicJAXBContext jaxbContext = OxmModelLoader.getContextForVersion(version);
252 final DynamicType modelObjectType = OxmModelLoader.getDynamicTypeForVersion(version, type);
253 final DynamicType reservedType = jaxbContext.getDynamicType("ReservedPropNames");
255 Set<Map.Entry<String, JsonElement>> payloadEntriesSet = properties.getAsJsonObject().entrySet();
257 // Loop through the payload properties and merge with existing
259 for (Map.Entry<String, JsonElement> entry : payloadEntriesSet) {
261 String keyJavaName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, entry.getKey());
263 DatabaseField field = null;
264 String defaultValue = null;
266 if (modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName) != null) {
267 field = modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName).getField();
268 defaultValue = modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName).getProperties()
269 .get("defaultValue") == null ? ""
270 : modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName).getProperties()
271 .get("defaultValue").toString();
272 } else if (reservedType.getDescriptor().getMappingForAttributeName(keyJavaName) != null) {
273 field = reservedType.getDescriptor().getMappingForAttributeName(keyJavaName).getField();
278 throw new CrudException("Invalid field: " + entry.getKey(), Status.BAD_REQUEST);
281 // check if mandatory field is not set to null
282 if (((XMLField) field).isRequired() && entry.getValue() instanceof JsonNull && !defaultValue.isEmpty()) {
283 existingVertex.getProperties().put(entry.getKey(),
284 CrudServiceUtil.validateFieldType(defaultValue, field.getType()));
285 } else if (((XMLField) field).isRequired() && entry.getValue() instanceof JsonNull && defaultValue.isEmpty()) {
286 throw new CrudException("Mandatory field: " + entry.getKey() + " can't be set to null", Status.BAD_REQUEST);
287 } else if (!((XMLField) field).isRequired() && entry.getValue() instanceof JsonNull
288 && existingVertex.getProperties().containsKey(entry.getKey())) {
289 existingVertex.getProperties().remove(entry.getKey());
290 } else if (!(entry.getValue() instanceof JsonNull)) {
291 // add/update the value if found in existing vertex
292 Object value = CrudServiceUtil.validateFieldType(entry.getValue().getAsString(), field.getType());
293 existingVertex.getProperties().put(entry.getKey(), value);
297 return existingVertex;
298 } catch (Exception e) {
299 throw new CrudException(e.getMessage(), Status.BAD_REQUEST);
303 private static DatabaseField getDatabaseField(String fieldName, DynamicType modelObjectType) {
304 for (DatabaseField field : modelObjectType.getDescriptor().getAllFields()) {
305 int ix = field.getName().indexOf("/");
307 ix = field.getName().length();
310 String keyName = field.getName().substring(0, ix);
311 if (fieldName.equals(keyName)) {
318 public static Vertex validateOutgoingPayload(String version, Vertex vertex) {
319 Vertex.Builder modelVertexBuilder = new Vertex.Builder(vertex.getType()).id(vertex.getId().get());
322 DynamicJAXBContext jaxbContext = OxmModelLoader.getContextForVersion(version);
324 final DynamicType modelObjectType = OxmModelLoader.getDynamicTypeForVersion(version,
325 vertex.getProperties().get(Metadata.NODE_TYPE.propertyName()) != null
326 ? vertex.getProperties().get(Metadata.NODE_TYPE.propertyName()).toString()
328 final DynamicType reservedObjectType = jaxbContext.getDynamicType("ReservedPropNames");
330 for (String key : vertex.getProperties().keySet()) {
331 DatabaseField field = getDatabaseField(key, modelObjectType);
333 field = getDatabaseField(key, reservedObjectType);
336 modelVertexBuilder.property(key, vertex.getProperties().get(key));
340 return modelVertexBuilder.build();
341 } catch (Exception ex) {