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 = jaxbContext.getDynamicType(
92 CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, type)));
93 final DynamicType reservedObjectType = jaxbContext.getDynamicType("ReservedPropNames");
95 for (String key : filter.keySet()) {
96 if ((key == CrudServiceConstants.CRD_RESERVED_VERSION ) || key == CrudServiceConstants.CRD_RESERVED_NODE_TYPE ) {
97 result.put ( key, filter.get ( key ) );
100 String keyJavaName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, key);
101 DatabaseMapping mapping = modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName);
103 // Try both the model for the specified type and the reserved properties for our key
104 if (mapping == null) {
105 mapping = reservedObjectType.getDescriptor().getMappingForAttributeName(keyJavaName);
107 if (mapping != null) {
109 Object value = CrudServiceUtil.validateFieldType(filter.get(key), mapping.getField().getType());
110 result.put(key, value);
111 } catch (Exception ex) {
112 // Skip any exceptions thrown while validating the filter
123 public static String resolveCollectionType(String version, String type) throws CrudException {
125 DynamicJAXBContext jaxbContext = null;
127 jaxbContext = OxmModelLoader.getContextForVersion(version);
128 } catch (CrudException ce) {
129 throw new CrudException(ce.getMessage(), ce.getHttpStatus());
130 } catch (Exception e) {
131 throw new CrudException(e);
134 if (jaxbContext == null) {
135 logger.error(CrudServiceMsgs.OXM_LOAD_ERROR, OXM_LOAD_ERROR + ": " + version);
136 throw new CrudException(OXM_LOAD_ERROR + ": " + version, Status.NOT_FOUND);
138 // Determine if the Object part is a collection type in the model
140 final DynamicType modelObjectType = jaxbContext.getDynamicType(
141 CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, type)));
143 if (modelObjectType == null) {
144 logger.error(CrudServiceMsgs.INVALID_OXM_FILE, "Object of collection type not found: " + type);
145 throw new CrudException("Object of collection type not found: " + type, Status.NOT_FOUND);
148 if (modelObjectType.getDescriptor().getMappings().size() == 1
149 && modelObjectType.getDescriptor().getMappings().get(0).isCollectionMapping()) {
150 String childJavaObjectName = modelObjectType.getDescriptor().getMappings().get(0).getAttributeName();
151 childJavaObjectName = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, childJavaObjectName);
152 final DynamicType childObjectType = jaxbContext.getDynamicType(childJavaObjectName);
153 if (childObjectType == null) {
154 // Should not happen as child object is defined in oxm model itself
155 logger.error(CrudServiceMsgs.INVALID_OXM_FILE, "Child Object Type for Java Object not found: " + childJavaObjectName);
156 throw new CrudException("Child Object Type for Java Object not found: " + childJavaObjectName, Status.NOT_FOUND);
158 return childObjectType.getDescriptor().getTableName();
160 return modelObjectType.getDescriptor().getTableName();
165 public static Vertex validateIncomingUpsertPayload(String id, String version, String type, JsonElement properties)
166 throws CrudException {
169 type = resolveCollectionType(version, type);
170 DynamicJAXBContext jaxbContext = OxmModelLoader.getContextForVersion(version);
171 String modelObjectClass = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL,
172 CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, type));
174 final DynamicType modelObjectType = jaxbContext.getDynamicType(modelObjectClass);
175 final DynamicType reservedType = jaxbContext.getDynamicType("ReservedPropNames");
177 Set<Map.Entry<String, JsonElement>> payloadEntriesSet = properties.getAsJsonObject().entrySet();
179 // loop through input to validate against schema
180 for (Map.Entry<String, JsonElement> entry : payloadEntriesSet) {
181 String keyJavaName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, entry.getKey());
183 // check for valid field
184 if (modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName) == null) {
185 if (reservedType.getDescriptor().getMappingForAttributeName(keyJavaName) == null) {
186 throw new CrudException("Invalid field: " + entry.getKey(), Status.BAD_REQUEST);
192 Map<String, JsonElement> entriesMap = new HashMap<String, JsonElement>();
193 for (Map.Entry<String, JsonElement> entry : payloadEntriesSet) {
194 entriesMap.put(entry.getKey(), entry.getValue());
197 Vertex.Builder modelVertexBuilder = new Vertex.Builder(type);
199 modelVertexBuilder.id(id);
201 for (DatabaseMapping mapping : modelObjectType.getDescriptor().getMappings()) {
202 if (mapping.isAbstractDirectMapping()) {
203 DatabaseField field = mapping.getField();
204 String defaultValue = mapping.getProperties().get("defaultValue") == null ? ""
205 : mapping.getProperties().get("defaultValue").toString();
207 String keyName = field.getName().substring(0, field.getName().indexOf("/"));
209 if (((XMLField) field).isRequired() && !entriesMap.containsKey(keyName) && !defaultValue.isEmpty()) {
210 modelVertexBuilder.property(keyName, CrudServiceUtil.validateFieldType(defaultValue, field.getType()));
212 // if schema field is required and not set then reject
213 if (((XMLField) field).isRequired() && !entriesMap.containsKey(keyName) && defaultValue.isEmpty()) {
214 throw new CrudException("Missing required field: " + keyName, Status.BAD_REQUEST);
216 // If invalid field then reject
217 if (entriesMap.containsKey(keyName)) {
218 Object value = CrudServiceUtil.validateFieldType(entriesMap.get(keyName).getAsString(), field.getType());
219 modelVertexBuilder.property(keyName, value);
223 if (!defaultValue.isEmpty() && !entriesMap.containsKey(keyName)) {
224 modelVertexBuilder.property(keyName, CrudServiceUtil.validateFieldType(defaultValue, field.getType()));
229 // Handle reserved properties
230 for (DatabaseMapping mapping : reservedType.getDescriptor().getMappings()) {
231 if (mapping.isAbstractDirectMapping()) {
232 DatabaseField field = mapping.getField();
233 String keyName = field.getName().substring(0, field.getName().indexOf("/"));
235 if (entriesMap.containsKey(keyName)) {
236 Object value = CrudServiceUtil.validateFieldType(entriesMap.get(keyName).getAsString(), field.getType());
237 modelVertexBuilder.property(keyName, value);
242 return modelVertexBuilder.build();
243 } catch (CrudException ce) {
244 throw new CrudException(ce.getMessage(), ce.getHttpStatus());
245 } catch (Exception e) {
246 throw new CrudException(e.getMessage(), Status.BAD_REQUEST);
250 public static Vertex validateIncomingPatchPayload(String id, String version, String type, JsonElement properties,
251 Vertex existingVertex) throws CrudException {
253 type = resolveCollectionType(version, type);
254 DynamicJAXBContext jaxbContext = OxmModelLoader.getContextForVersion(version);
255 String modelObjectClass = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL,
256 CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, type));
258 final DynamicType modelObjectType = jaxbContext.getDynamicType(modelObjectClass);
259 final DynamicType reservedType = jaxbContext.getDynamicType("ReservedPropNames");
261 Set<Map.Entry<String, JsonElement>> payloadEntriesSet = properties.getAsJsonObject().entrySet();
263 // Loop through the payload properties and merge with existing
265 for (Map.Entry<String, JsonElement> entry : payloadEntriesSet) {
267 String keyJavaName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, entry.getKey());
269 DatabaseField field = null;
270 String defaultValue = null;
272 if (modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName) != null) {
273 field = modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName).getField();
274 defaultValue = modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName).getProperties()
275 .get("defaultValue") == null ? ""
276 : modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName).getProperties()
277 .get("defaultValue").toString();
278 } else if (reservedType.getDescriptor().getMappingForAttributeName(keyJavaName) != null) {
279 field = reservedType.getDescriptor().getMappingForAttributeName(keyJavaName).getField();
284 throw new CrudException("Invalid field: " + entry.getKey(), Status.BAD_REQUEST);
287 // check if mandatory field is not set to null
288 if (((XMLField) field).isRequired() && entry.getValue() instanceof JsonNull && !defaultValue.isEmpty()) {
289 existingVertex.getProperties().put(entry.getKey(),
290 CrudServiceUtil.validateFieldType(defaultValue, field.getType()));
291 } else if (((XMLField) field).isRequired() && entry.getValue() instanceof JsonNull && defaultValue.isEmpty()) {
292 throw new CrudException("Mandatory field: " + entry.getKey() + " can't be set to null", Status.BAD_REQUEST);
293 } else if (!((XMLField) field).isRequired() && entry.getValue() instanceof JsonNull
294 && existingVertex.getProperties().containsKey(entry.getKey())) {
295 existingVertex.getProperties().remove(entry.getKey());
296 } else if (!(entry.getValue() instanceof JsonNull)) {
297 // add/update the value if found in existing vertex
298 Object value = CrudServiceUtil.validateFieldType(entry.getValue().getAsString(), field.getType());
299 existingVertex.getProperties().put(entry.getKey(), value);
303 return existingVertex;
304 } catch (Exception e) {
305 throw new CrudException(e.getMessage(), Status.BAD_REQUEST);
309 private static DatabaseField getDatabaseField(String fieldName, DynamicType modelObjectType) {
310 for (DatabaseField field : modelObjectType.getDescriptor().getAllFields()) {
311 int ix = field.getName().indexOf("/");
313 ix = field.getName().length();
316 String keyName = field.getName().substring(0, ix);
317 if (fieldName.equals(keyName)) {
324 public static Vertex validateOutgoingPayload(String version, Vertex vertex) {
325 Vertex.Builder modelVertexBuilder = new Vertex.Builder(vertex.getType()).id(vertex.getId().get());
328 DynamicJAXBContext jaxbContext = OxmModelLoader.getContextForVersion(version);
329 String modelObjectClass = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL,
330 CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL,
331 vertex.getProperties().get(Metadata.NODE_TYPE.propertyName()) != null
332 ? vertex.getProperties().get(Metadata.NODE_TYPE.propertyName()).toString() : vertex.getType()));
333 final DynamicType modelObjectType = jaxbContext.getDynamicType(modelObjectClass);
334 final DynamicType reservedObjectType = jaxbContext.getDynamicType("ReservedPropNames");
336 for (String key : vertex.getProperties().keySet()) {
337 DatabaseField field = getDatabaseField(key, modelObjectType);
339 field = getDatabaseField(key, reservedObjectType);
342 modelVertexBuilder.property(key, vertex.getProperties().get(key));
346 return modelVertexBuilder.build();
347 } catch (Exception ex) {