2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright © 2017 AT&T Intellectual Property.
6 * Copyright © 2017 Amdocs
8 * ================================================================================
9 * Licensed under the Apache License, Version 2.0 (the "License");
10 * you may not use this file except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
20 * ============LICENSE_END=========================================================
22 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
24 package org.onap.schema;
26 import com.google.common.base.CaseFormat;
27 import com.google.gson.JsonElement;
28 import com.google.gson.JsonNull;
30 import org.eclipse.persistence.dynamic.DynamicType;
31 import org.eclipse.persistence.internal.helper.DatabaseField;
32 import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext;
33 import org.eclipse.persistence.mappings.DatabaseMapping;
34 import org.eclipse.persistence.oxm.XMLField;
35 import org.onap.aaiutils.oxm.OxmModelLoader;
36 import org.onap.crud.entity.Vertex;
37 import org.onap.crud.exception.CrudException;
38 import org.onap.crud.util.CrudServiceUtil;
40 import java.util.HashMap;
43 import javax.ws.rs.core.Response.Status;
45 public class OxmModelValidator {
46 public enum Metadata {
47 NODE_TYPE("aai-node-type"), URI("aai-uri"), CREATED_TS("aai-created-ts"), SOT("source-of-truth"), LAST_MOD_SOT(
48 "last-mod-source-of-truth");
50 private final String propName;
52 Metadata(String propName) {
53 this.propName = propName;
56 public String propertyName() {
60 public static boolean isProperty(String property) {
61 for (Metadata meta : Metadata.values()) {
62 if (meta.propName.equals(property)) {
70 public static Map<String, Object> resolveCollectionfilter(String version, String type, Map<String, String> filter)
71 throws CrudException {
73 DynamicJAXBContext jaxbContext = null;
75 jaxbContext = OxmModelLoader.getContextForVersion(version);
76 } catch (Exception e) {
77 throw new CrudException(e);
80 Map<String, Object> result = new HashMap<String, Object>();
81 if (jaxbContext == null) {
82 throw new CrudException("", Status.NOT_FOUND);
84 final DynamicType modelObjectType = jaxbContext.getDynamicType(
85 CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, type)));
87 for (String key : filter.keySet()) {
88 String keyJavaName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, key);
89 if (modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName) != null) {
91 DatabaseMapping mapping = modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName);
92 Object value = CrudServiceUtil.validateFieldType(filter.get(key), mapping.getField().getType());
93 result.put(key, value);
94 } catch (Exception ex) {
95 // Skip any exceptions thrown while validating the filter
106 public static String resolveCollectionType(String version, String type) throws CrudException {
108 DynamicJAXBContext jaxbContext = null;
110 jaxbContext = OxmModelLoader.getContextForVersion(version);
111 } catch (Exception e) {
112 throw new CrudException(e);
115 if (jaxbContext == null) {
116 throw new CrudException("", Status.NOT_FOUND);
118 // Determine if the Object part is a collection type in the model
120 final DynamicType modelObjectType = jaxbContext.getDynamicType(
121 CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, type)));
123 if (modelObjectType == null) {
124 throw new CrudException("", Status.NOT_FOUND);
127 if (modelObjectType.getDescriptor().getMappings().size() == 1
128 && modelObjectType.getDescriptor().getMappings().get(0).isCollectionMapping()) {
129 String childJavaObjectName = modelObjectType.getDescriptor().getMappings().get(0).getAttributeName();
130 childJavaObjectName = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, childJavaObjectName);
131 final DynamicType childObjectType = jaxbContext.getDynamicType(childJavaObjectName);
132 if (childObjectType == null) {
133 // Should not happen as child object is defined in oxm model
135 throw new CrudException("", Status.NOT_FOUND);
137 return childObjectType.getDescriptor().getTableName();
139 return modelObjectType.getDescriptor().getTableName();
144 public static Vertex validateIncomingUpsertPayload(String id, String version, String type, JsonElement properties)
145 throws CrudException {
148 type = resolveCollectionType(version, type);
149 DynamicJAXBContext jaxbContext = OxmModelLoader.getContextForVersion(version);
150 String modelObjectClass = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL,
151 CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, type));
153 final DynamicType modelObjectType = jaxbContext.getDynamicType(modelObjectClass);
154 final DynamicType reservedType = jaxbContext.getDynamicType("ReservedPropNames");
156 Set<Map.Entry<String, JsonElement>> payloadEntriesSet = properties.getAsJsonObject().entrySet();
158 // loop through input to validate against schema
159 for (Map.Entry<String, JsonElement> entry : payloadEntriesSet) {
160 String keyJavaName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, entry.getKey());
162 // check for valid field
163 if (modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName) == null) {
164 if (reservedType.getDescriptor().getMappingForAttributeName(keyJavaName) == null) {
165 throw new CrudException("Invalid field: " + entry.getKey(), Status.BAD_REQUEST);
171 Map<String, JsonElement> entriesMap = new HashMap<String, JsonElement>();
172 for (Map.Entry<String, JsonElement> entry : payloadEntriesSet) {
173 entriesMap.put(entry.getKey(), entry.getValue());
176 Vertex.Builder modelVertexBuilder = new Vertex.Builder(type);
178 modelVertexBuilder.id(id);
180 for (DatabaseMapping mapping : modelObjectType.getDescriptor().getMappings()) {
181 if (mapping.isAbstractDirectMapping()) {
182 DatabaseField field = mapping.getField();
183 String defaultValue = mapping.getProperties().get("defaultValue") == null ? ""
184 : mapping.getProperties().get("defaultValue").toString();
186 String keyName = field.getName().substring(0, field.getName().indexOf("/"));
188 if (((XMLField) field).isRequired() && !entriesMap.containsKey(keyName) && !defaultValue.isEmpty()) {
189 modelVertexBuilder.property(keyName, CrudServiceUtil.validateFieldType(defaultValue, field.getType()));
191 // if schema field is required and not set then reject
192 if (((XMLField) field).isRequired() && !entriesMap.containsKey(keyName) && defaultValue.isEmpty()) {
193 throw new CrudException("Missing required field: " + keyName, Status.BAD_REQUEST);
195 // If invalid field then reject
196 if (entriesMap.containsKey(keyName)) {
197 Object value = CrudServiceUtil.validateFieldType(entriesMap.get(keyName).getAsString(), field.getType());
198 modelVertexBuilder.property(keyName, value);
202 if (!defaultValue.isEmpty() && !entriesMap.containsKey(keyName)) {
203 modelVertexBuilder.property(keyName, CrudServiceUtil.validateFieldType(defaultValue, field.getType()));
208 // Handle reserved properties
209 for (DatabaseMapping mapping : reservedType.getDescriptor().getMappings()) {
210 if (mapping.isAbstractDirectMapping()) {
211 DatabaseField field = mapping.getField();
212 String keyName = field.getName().substring(0, field.getName().indexOf("/"));
214 if (entriesMap.containsKey(keyName)) {
215 Object value = CrudServiceUtil.validateFieldType(entriesMap.get(keyName).getAsString(), field.getType());
216 modelVertexBuilder.property(keyName, value);
221 return modelVertexBuilder.build();
222 } catch (Exception e) {
223 throw new CrudException(e.getMessage(), Status.BAD_REQUEST);
227 public static Vertex validateIncomingPatchPayload(String id, String version, String type, JsonElement properties,
228 Vertex existingVertex) throws CrudException {
231 type = resolveCollectionType(version, type);
232 DynamicJAXBContext jaxbContext = OxmModelLoader.getContextForVersion(version);
233 String modelObjectClass = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL,
234 CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, type));
236 final DynamicType modelObjectType = jaxbContext.getDynamicType(modelObjectClass);
237 final DynamicType reservedType = jaxbContext.getDynamicType("ReservedPropNames");
239 Set<Map.Entry<String, JsonElement>> payloadEntriesSet = properties.getAsJsonObject().entrySet();
241 // Loop through the payload properties and merge with existing
243 for (Map.Entry<String, JsonElement> entry : payloadEntriesSet) {
245 String keyJavaName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, entry.getKey());
247 DatabaseField field = null;
248 String defaultValue = null;
250 if (modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName) != null) {
251 field = modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName).getField();
252 defaultValue = modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName).getProperties()
253 .get("defaultValue") == null ? ""
254 : modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName).getProperties()
255 .get("defaultValue").toString();
256 } else if (reservedType.getDescriptor().getMappingForAttributeName(keyJavaName) != null) {
257 field = reservedType.getDescriptor().getMappingForAttributeName(keyJavaName).getField();
262 throw new CrudException("Invalid field: " + entry.getKey(), Status.BAD_REQUEST);
265 // check if mandatory field is not set to null
266 if (((XMLField) field).isRequired() && entry.getValue() instanceof JsonNull && !defaultValue.isEmpty()) {
267 existingVertex.getProperties().put(entry.getKey(),
268 CrudServiceUtil.validateFieldType(defaultValue, field.getType()));
269 } else if (((XMLField) field).isRequired() && entry.getValue() instanceof JsonNull && defaultValue.isEmpty()) {
270 throw new CrudException("Mandatory field: " + entry.getKey() + " can't be set to null", Status.BAD_REQUEST);
271 } else if (!((XMLField) field).isRequired() && entry.getValue() instanceof JsonNull
272 && existingVertex.getProperties().containsKey(entry.getKey())) {
273 existingVertex.getProperties().remove(entry.getKey());
274 } else if (!(entry.getValue() instanceof JsonNull)) {
275 // add/update the value if found in existing vertex
276 Object value = CrudServiceUtil.validateFieldType(entry.getValue().getAsString(), field.getType());
277 existingVertex.getProperties().put(entry.getKey(), value);
282 return existingVertex;
283 } catch (Exception e) {
284 throw new CrudException(e.getMessage(), Status.BAD_REQUEST);
289 private static DatabaseField getDatabaseField(String fieldName, DynamicType modelObjectType) {
290 for (DatabaseField field : modelObjectType.getDescriptor().getAllFields()) {
291 int ix = field.getName().indexOf("/");
293 ix = field.getName().length();
296 String keyName = field.getName().substring(0, ix);
297 if (fieldName.equals(keyName)) {
304 public static Vertex validateOutgoingPayload(String version, Vertex vertex) {
306 Vertex.Builder modelVertexBuilder = new Vertex.Builder(vertex.getType()).id(vertex.getId().get());
309 DynamicJAXBContext jaxbContext = OxmModelLoader.getContextForVersion(version);
310 String modelObjectClass = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL,
311 CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL,
312 vertex.getProperties().get(Metadata.NODE_TYPE.propertyName()) != null
313 ? vertex.getProperties().get(Metadata.NODE_TYPE.propertyName()).toString() : vertex.getType()));
314 final DynamicType modelObjectType = jaxbContext.getDynamicType(modelObjectClass);
316 for (String key : vertex.getProperties().keySet()) {
317 DatabaseField field = getDatabaseField(key, modelObjectType);
319 if (!Metadata.isProperty(key)) {
320 modelVertexBuilder.property(key, vertex.getProperties().get(key));
324 return modelVertexBuilder.build();
325 } catch (Exception ex) {