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.CrudServiceConstants;
36 import org.onap.crud.util.CrudServiceUtil;
38 import java.util.HashMap;
41 import javax.ws.rs.core.Response.Status;
43 public class OxmModelValidator {
44 public enum Metadata {
45 NODE_TYPE("aai-node-type"),
47 CREATED_TS("aai-created-ts"),
48 UPDATED_TS("aai-last-mod-ts"),
49 SOT("source-of-truth"),
50 LAST_MOD_SOT("last-mod-source-of-truth");
52 private final String propName;
54 Metadata(String propName) {
55 this.propName = propName;
58 public String propertyName() {
62 public static boolean isProperty(String property) {
63 for (Metadata meta : Metadata.values()) {
64 if (meta.propName.equals(property)) {
72 public static Map<String, Object> resolveCollectionfilter(String version, String type, Map<String, String> filter)
73 throws CrudException {
75 DynamicJAXBContext jaxbContext = null;
77 jaxbContext = OxmModelLoader.getContextForVersion(version);
78 } catch (Exception e) {
79 throw new CrudException(e);
82 Map<String, Object> result = new HashMap<String, Object>();
83 if (jaxbContext == null) {
84 throw new CrudException("", Status.NOT_FOUND);
86 final DynamicType modelObjectType = jaxbContext.getDynamicType(
87 CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, type)));
88 final DynamicType reservedObjectType = jaxbContext.getDynamicType("ReservedPropNames");
90 for (String key : filter.keySet()) {
91 if ((key == CrudServiceConstants.CRD_RESERVED_VERSION ) || key == CrudServiceConstants.CRD_RESERVED_NODE_TYPE ) {
92 result.put ( key, filter.get ( key ) );
95 String keyJavaName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, key);
96 DatabaseMapping mapping = modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName);
98 // Try both the model for the specified type and the reserved properties for our key
99 if (mapping == null) {
100 mapping = reservedObjectType.getDescriptor().getMappingForAttributeName(keyJavaName);
102 if (mapping != null) {
104 Object value = CrudServiceUtil.validateFieldType(filter.get(key), mapping.getField().getType());
105 result.put(key, value);
106 } catch (Exception ex) {
107 // Skip any exceptions thrown while validating the filter
118 public static String resolveCollectionType(String version, String type) throws CrudException {
120 DynamicJAXBContext jaxbContext = null;
122 jaxbContext = OxmModelLoader.getContextForVersion(version);
123 } catch (Exception e) {
124 throw new CrudException(e);
127 if (jaxbContext == null) {
128 throw new CrudException("", Status.NOT_FOUND);
130 // Determine if the Object part is a collection type in the model
132 final DynamicType modelObjectType = jaxbContext.getDynamicType(
133 CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, type)));
135 if (modelObjectType == null) {
136 throw new CrudException("", Status.NOT_FOUND);
139 if (modelObjectType.getDescriptor().getMappings().size() == 1
140 && modelObjectType.getDescriptor().getMappings().get(0).isCollectionMapping()) {
141 String childJavaObjectName = modelObjectType.getDescriptor().getMappings().get(0).getAttributeName();
142 childJavaObjectName = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, childJavaObjectName);
143 final DynamicType childObjectType = jaxbContext.getDynamicType(childJavaObjectName);
144 if (childObjectType == null) {
145 // Should not happen as child object is defined in oxm model
147 throw new CrudException("", Status.NOT_FOUND);
149 return childObjectType.getDescriptor().getTableName();
151 return modelObjectType.getDescriptor().getTableName();
156 public static Vertex validateIncomingUpsertPayload(String id, String version, String type, JsonElement properties)
157 throws CrudException {
160 type = resolveCollectionType(version, type);
161 DynamicJAXBContext jaxbContext = OxmModelLoader.getContextForVersion(version);
162 String modelObjectClass = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL,
163 CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, type));
165 final DynamicType modelObjectType = jaxbContext.getDynamicType(modelObjectClass);
166 final DynamicType reservedType = jaxbContext.getDynamicType("ReservedPropNames");
168 Set<Map.Entry<String, JsonElement>> payloadEntriesSet = properties.getAsJsonObject().entrySet();
170 // loop through input to validate against schema
171 for (Map.Entry<String, JsonElement> entry : payloadEntriesSet) {
172 String keyJavaName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, entry.getKey());
174 // check for valid field
175 if (modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName) == null) {
176 if (reservedType.getDescriptor().getMappingForAttributeName(keyJavaName) == null) {
177 throw new CrudException("Invalid field: " + entry.getKey(), Status.BAD_REQUEST);
183 Map<String, JsonElement> entriesMap = new HashMap<String, JsonElement>();
184 for (Map.Entry<String, JsonElement> entry : payloadEntriesSet) {
185 entriesMap.put(entry.getKey(), entry.getValue());
188 Vertex.Builder modelVertexBuilder = new Vertex.Builder(type);
190 modelVertexBuilder.id(id);
192 for (DatabaseMapping mapping : modelObjectType.getDescriptor().getMappings()) {
193 if (mapping.isAbstractDirectMapping()) {
194 DatabaseField field = mapping.getField();
195 String defaultValue = mapping.getProperties().get("defaultValue") == null ? ""
196 : mapping.getProperties().get("defaultValue").toString();
198 String keyName = field.getName().substring(0, field.getName().indexOf("/"));
200 if (((XMLField) field).isRequired() && !entriesMap.containsKey(keyName) && !defaultValue.isEmpty()) {
201 modelVertexBuilder.property(keyName, CrudServiceUtil.validateFieldType(defaultValue, field.getType()));
203 // if schema field is required and not set then reject
204 if (((XMLField) field).isRequired() && !entriesMap.containsKey(keyName) && defaultValue.isEmpty()) {
205 throw new CrudException("Missing required field: " + keyName, Status.BAD_REQUEST);
207 // If invalid field then reject
208 if (entriesMap.containsKey(keyName)) {
209 Object value = CrudServiceUtil.validateFieldType(entriesMap.get(keyName).getAsString(), field.getType());
210 modelVertexBuilder.property(keyName, value);
214 if (!defaultValue.isEmpty() && !entriesMap.containsKey(keyName)) {
215 modelVertexBuilder.property(keyName, CrudServiceUtil.validateFieldType(defaultValue, field.getType()));
220 // Handle reserved properties
221 for (DatabaseMapping mapping : reservedType.getDescriptor().getMappings()) {
222 if (mapping.isAbstractDirectMapping()) {
223 DatabaseField field = mapping.getField();
224 String keyName = field.getName().substring(0, field.getName().indexOf("/"));
226 if (entriesMap.containsKey(keyName)) {
227 Object value = CrudServiceUtil.validateFieldType(entriesMap.get(keyName).getAsString(), field.getType());
228 modelVertexBuilder.property(keyName, value);
233 return modelVertexBuilder.build();
234 } catch (Exception e) {
235 throw new CrudException(e.getMessage(), Status.BAD_REQUEST);
239 public static Vertex validateIncomingPatchPayload(String id, String version, String type, JsonElement properties,
240 Vertex existingVertex) throws CrudException {
242 type = resolveCollectionType(version, type);
243 DynamicJAXBContext jaxbContext = OxmModelLoader.getContextForVersion(version);
244 String modelObjectClass = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL,
245 CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, type));
247 final DynamicType modelObjectType = jaxbContext.getDynamicType(modelObjectClass);
248 final DynamicType reservedType = jaxbContext.getDynamicType("ReservedPropNames");
250 Set<Map.Entry<String, JsonElement>> payloadEntriesSet = properties.getAsJsonObject().entrySet();
252 // Loop through the payload properties and merge with existing
254 for (Map.Entry<String, JsonElement> entry : payloadEntriesSet) {
256 String keyJavaName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, entry.getKey());
258 DatabaseField field = null;
259 String defaultValue = null;
261 if (modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName) != null) {
262 field = modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName).getField();
263 defaultValue = modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName).getProperties()
264 .get("defaultValue") == null ? ""
265 : modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName).getProperties()
266 .get("defaultValue").toString();
267 } else if (reservedType.getDescriptor().getMappingForAttributeName(keyJavaName) != null) {
268 field = reservedType.getDescriptor().getMappingForAttributeName(keyJavaName).getField();
273 throw new CrudException("Invalid field: " + entry.getKey(), Status.BAD_REQUEST);
276 // check if mandatory field is not set to null
277 if (((XMLField) field).isRequired() && entry.getValue() instanceof JsonNull && !defaultValue.isEmpty()) {
278 existingVertex.getProperties().put(entry.getKey(),
279 CrudServiceUtil.validateFieldType(defaultValue, field.getType()));
280 } else if (((XMLField) field).isRequired() && entry.getValue() instanceof JsonNull && defaultValue.isEmpty()) {
281 throw new CrudException("Mandatory field: " + entry.getKey() + " can't be set to null", Status.BAD_REQUEST);
282 } else if (!((XMLField) field).isRequired() && entry.getValue() instanceof JsonNull
283 && existingVertex.getProperties().containsKey(entry.getKey())) {
284 existingVertex.getProperties().remove(entry.getKey());
285 } else if (!(entry.getValue() instanceof JsonNull)) {
286 // add/update the value if found in existing vertex
287 Object value = CrudServiceUtil.validateFieldType(entry.getValue().getAsString(), field.getType());
288 existingVertex.getProperties().put(entry.getKey(), value);
292 return existingVertex;
293 } catch (Exception e) {
294 throw new CrudException(e.getMessage(), Status.BAD_REQUEST);
298 private static DatabaseField getDatabaseField(String fieldName, DynamicType modelObjectType) {
299 for (DatabaseField field : modelObjectType.getDescriptor().getAllFields()) {
300 int ix = field.getName().indexOf("/");
302 ix = field.getName().length();
305 String keyName = field.getName().substring(0, ix);
306 if (fieldName.equals(keyName)) {
313 public static Vertex validateOutgoingPayload(String version, Vertex vertex) {
314 Vertex.Builder modelVertexBuilder = new Vertex.Builder(vertex.getType()).id(vertex.getId().get());
317 DynamicJAXBContext jaxbContext = OxmModelLoader.getContextForVersion(version);
318 String modelObjectClass = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL,
319 CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL,
320 vertex.getProperties().get(Metadata.NODE_TYPE.propertyName()) != null
321 ? vertex.getProperties().get(Metadata.NODE_TYPE.propertyName()).toString() : vertex.getType()));
322 final DynamicType modelObjectType = jaxbContext.getDynamicType(modelObjectClass);
323 final DynamicType reservedObjectType = jaxbContext.getDynamicType("ReservedPropNames");
325 for (String key : vertex.getProperties().keySet()) {
326 DatabaseField field = getDatabaseField(key, modelObjectType);
328 field = getDatabaseField(key, reservedObjectType);
331 modelVertexBuilder.property(key, vertex.getProperties().get(key));
335 return modelVertexBuilder.build();
336 } catch (Exception ex) {