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 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 com.google.common.base.CaseFormat;
40 import com.google.gson.JsonElement;
41 import com.google.gson.JsonNull;
43 public class OxmModelValidator {
44 private static Logger logger = LoggerFactory.getInstance().getLogger(OxmModelValidator.class.getName());
46 public enum Metadata {
47 NODE_TYPE("aai-node-type"),
49 CREATED_TS("aai-created-ts"),
50 UPDATED_TS("aai-last-mod-ts"),
51 SOT("source-of-truth"),
52 LAST_MOD_SOT("last-mod-source-of-truth");
54 private final String propName;
56 Metadata(String propName) {
57 this.propName = propName;
60 public String propertyName() {
64 public static boolean isProperty(String property) {
65 for (Metadata meta : Metadata.values()) {
66 if (meta.propName.equals(property)) {
74 public static Map<String, Object> resolveCollectionfilter(String version, String type, Map<String, String> filter)
75 throws CrudException {
77 DynamicJAXBContext jaxbContext = null;
79 jaxbContext = OxmModelLoader.getContextForVersion(version);
80 } catch (Exception e) {
81 throw new CrudException(e);
84 Map<String, Object> result = new HashMap<String, Object>();
85 if (jaxbContext == null) {
86 logger.error(CrudServiceMsgs.OXM_LOAD_ERROR, "Error loading oxm model: " + version);
87 throw new CrudException("Error loading oxm model: " + version, Status.NOT_FOUND);
89 final DynamicType modelObjectType = jaxbContext.getDynamicType(
90 CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, type)));
91 final DynamicType reservedObjectType = jaxbContext.getDynamicType("ReservedPropNames");
93 for (String key : filter.keySet()) {
94 if ((key == CrudServiceConstants.CRD_RESERVED_VERSION ) || key == CrudServiceConstants.CRD_RESERVED_NODE_TYPE ) {
95 result.put ( key, filter.get ( key ) );
98 String keyJavaName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, key);
99 DatabaseMapping mapping = modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName);
101 // Try both the model for the specified type and the reserved properties for our key
102 if (mapping == null) {
103 mapping = reservedObjectType.getDescriptor().getMappingForAttributeName(keyJavaName);
105 if (mapping != null) {
107 Object value = CrudServiceUtil.validateFieldType(filter.get(key), mapping.getField().getType());
108 result.put(key, value);
109 } catch (Exception ex) {
110 // Skip any exceptions thrown while validating the filter
121 public static String resolveCollectionType(String version, String type) throws CrudException {
123 DynamicJAXBContext jaxbContext = null;
125 jaxbContext = OxmModelLoader.getContextForVersion(version);
126 } catch (CrudException ce) {
127 throw new CrudException(ce.getMessage(), ce.getHttpStatus());
128 } catch (Exception e) {
129 throw new CrudException(e);
132 if (jaxbContext == null) {
133 logger.error(CrudServiceMsgs.OXM_LOAD_ERROR, "Error loading oxm model: " + version);
134 throw new CrudException("Error loading oxm model: " + version, Status.NOT_FOUND);
136 // Determine if the Object part is a collection type in the model
138 final DynamicType modelObjectType = jaxbContext.getDynamicType(
139 CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, 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);
169 String modelObjectClass = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL,
170 CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, type));
172 final DynamicType modelObjectType = jaxbContext.getDynamicType(modelObjectClass);
173 final DynamicType reservedType = jaxbContext.getDynamicType("ReservedPropNames");
175 Set<Map.Entry<String, JsonElement>> payloadEntriesSet = properties.getAsJsonObject().entrySet();
177 // loop through input to validate against schema
178 for (Map.Entry<String, JsonElement> entry : payloadEntriesSet) {
179 String keyJavaName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, entry.getKey());
181 // check for valid field
182 if (modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName) == null) {
183 if (reservedType.getDescriptor().getMappingForAttributeName(keyJavaName) == null) {
184 throw new CrudException("Invalid field: " + entry.getKey(), Status.BAD_REQUEST);
190 Map<String, JsonElement> entriesMap = new HashMap<String, JsonElement>();
191 for (Map.Entry<String, JsonElement> entry : payloadEntriesSet) {
192 entriesMap.put(entry.getKey(), entry.getValue());
195 Vertex.Builder modelVertexBuilder = new Vertex.Builder(type);
197 modelVertexBuilder.id(id);
199 for (DatabaseMapping mapping : modelObjectType.getDescriptor().getMappings()) {
200 if (mapping.isAbstractDirectMapping()) {
201 DatabaseField field = mapping.getField();
202 String defaultValue = mapping.getProperties().get("defaultValue") == null ? ""
203 : mapping.getProperties().get("defaultValue").toString();
205 String keyName = field.getName().substring(0, field.getName().indexOf("/"));
207 if (((XMLField) field).isRequired() && !entriesMap.containsKey(keyName) && !defaultValue.isEmpty()) {
208 modelVertexBuilder.property(keyName, CrudServiceUtil.validateFieldType(defaultValue, field.getType()));
210 // if schema field is required and not set then reject
211 if (((XMLField) field).isRequired() && !entriesMap.containsKey(keyName) && defaultValue.isEmpty()) {
212 throw new CrudException("Missing required field: " + keyName, Status.BAD_REQUEST);
214 // If invalid field then reject
215 if (entriesMap.containsKey(keyName)) {
216 Object value = CrudServiceUtil.validateFieldType(entriesMap.get(keyName).getAsString(), field.getType());
217 modelVertexBuilder.property(keyName, value);
221 if (!defaultValue.isEmpty() && !entriesMap.containsKey(keyName)) {
222 modelVertexBuilder.property(keyName, CrudServiceUtil.validateFieldType(defaultValue, field.getType()));
227 // Handle reserved properties
228 for (DatabaseMapping mapping : reservedType.getDescriptor().getMappings()) {
229 if (mapping.isAbstractDirectMapping()) {
230 DatabaseField field = mapping.getField();
231 String keyName = field.getName().substring(0, field.getName().indexOf("/"));
233 if (entriesMap.containsKey(keyName)) {
234 Object value = CrudServiceUtil.validateFieldType(entriesMap.get(keyName).getAsString(), field.getType());
235 modelVertexBuilder.property(keyName, value);
240 return modelVertexBuilder.build();
241 } catch (CrudException ce) {
242 throw new CrudException(ce.getMessage(), ce.getHttpStatus());
243 } catch (Exception e) {
244 throw new CrudException(e.getMessage(), Status.BAD_REQUEST);
248 public static Vertex validateIncomingPatchPayload(String id, String version, String type, JsonElement properties,
249 Vertex existingVertex) throws CrudException {
251 type = resolveCollectionType(version, type);
252 DynamicJAXBContext jaxbContext = OxmModelLoader.getContextForVersion(version);
253 String modelObjectClass = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL,
254 CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, type));
256 final DynamicType modelObjectType = jaxbContext.getDynamicType(modelObjectClass);
257 final DynamicType reservedType = jaxbContext.getDynamicType("ReservedPropNames");
259 Set<Map.Entry<String, JsonElement>> payloadEntriesSet = properties.getAsJsonObject().entrySet();
261 // Loop through the payload properties and merge with existing
263 for (Map.Entry<String, JsonElement> entry : payloadEntriesSet) {
265 String keyJavaName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, entry.getKey());
267 DatabaseField field = null;
268 String defaultValue = null;
270 if (modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName) != null) {
271 field = modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName).getField();
272 defaultValue = modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName).getProperties()
273 .get("defaultValue") == null ? ""
274 : modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName).getProperties()
275 .get("defaultValue").toString();
276 } else if (reservedType.getDescriptor().getMappingForAttributeName(keyJavaName) != null) {
277 field = reservedType.getDescriptor().getMappingForAttributeName(keyJavaName).getField();
282 throw new CrudException("Invalid field: " + entry.getKey(), Status.BAD_REQUEST);
285 // check if mandatory field is not set to null
286 if (((XMLField) field).isRequired() && entry.getValue() instanceof JsonNull && !defaultValue.isEmpty()) {
287 existingVertex.getProperties().put(entry.getKey(),
288 CrudServiceUtil.validateFieldType(defaultValue, field.getType()));
289 } else if (((XMLField) field).isRequired() && entry.getValue() instanceof JsonNull && defaultValue.isEmpty()) {
290 throw new CrudException("Mandatory field: " + entry.getKey() + " can't be set to null", Status.BAD_REQUEST);
291 } else if (!((XMLField) field).isRequired() && entry.getValue() instanceof JsonNull
292 && existingVertex.getProperties().containsKey(entry.getKey())) {
293 existingVertex.getProperties().remove(entry.getKey());
294 } else if (!(entry.getValue() instanceof JsonNull)) {
295 // add/update the value if found in existing vertex
296 Object value = CrudServiceUtil.validateFieldType(entry.getValue().getAsString(), field.getType());
297 existingVertex.getProperties().put(entry.getKey(), value);
301 return existingVertex;
302 } catch (Exception e) {
303 throw new CrudException(e.getMessage(), Status.BAD_REQUEST);
307 private static DatabaseField getDatabaseField(String fieldName, DynamicType modelObjectType) {
308 for (DatabaseField field : modelObjectType.getDescriptor().getAllFields()) {
309 int ix = field.getName().indexOf("/");
311 ix = field.getName().length();
314 String keyName = field.getName().substring(0, ix);
315 if (fieldName.equals(keyName)) {
322 public static Vertex validateOutgoingPayload(String version, Vertex vertex) {
323 Vertex.Builder modelVertexBuilder = new Vertex.Builder(vertex.getType()).id(vertex.getId().get());
326 DynamicJAXBContext jaxbContext = OxmModelLoader.getContextForVersion(version);
327 String modelObjectClass = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL,
328 CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL,
329 vertex.getProperties().get(Metadata.NODE_TYPE.propertyName()) != null
330 ? vertex.getProperties().get(Metadata.NODE_TYPE.propertyName()).toString() : vertex.getType()));
331 final DynamicType modelObjectType = jaxbContext.getDynamicType(modelObjectClass);
332 final DynamicType reservedObjectType = jaxbContext.getDynamicType("ReservedPropNames");
334 for (String key : vertex.getProperties().keySet()) {
335 DatabaseField field = getDatabaseField(key, modelObjectType);
337 field = getDatabaseField(key, reservedObjectType);
340 modelVertexBuilder.property(key, vertex.getProperties().get(key));
344 return modelVertexBuilder.build();
345 } catch (Exception ex) {