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"),
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 throw new CrudException("", Status.NOT_FOUND);
88 final DynamicType modelObjectType = jaxbContext.getDynamicType(
89 CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, type)));
91 for (String key : filter.keySet()) {
92 String keyJavaName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, key);
93 if (modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName) != null) {
95 DatabaseMapping mapping = modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName);
96 Object value = CrudServiceUtil.validateFieldType(filter.get(key), mapping.getField().getType());
97 result.put(key, value);
98 } catch (Exception ex) {
99 // Skip any exceptions thrown while validating the filter
110 public static String resolveCollectionType(String version, String type) throws CrudException {
112 DynamicJAXBContext jaxbContext = null;
114 jaxbContext = OxmModelLoader.getContextForVersion(version);
115 } catch (Exception e) {
116 throw new CrudException(e);
119 if (jaxbContext == null) {
120 throw new CrudException("", Status.NOT_FOUND);
122 // Determine if the Object part is a collection type in the model
124 final DynamicType modelObjectType = jaxbContext.getDynamicType(
125 CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, type)));
127 if (modelObjectType == null) {
128 throw new CrudException("", Status.NOT_FOUND);
131 if (modelObjectType.getDescriptor().getMappings().size() == 1
132 && modelObjectType.getDescriptor().getMappings().get(0).isCollectionMapping()) {
133 String childJavaObjectName = modelObjectType.getDescriptor().getMappings().get(0).getAttributeName();
134 childJavaObjectName = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, childJavaObjectName);
135 final DynamicType childObjectType = jaxbContext.getDynamicType(childJavaObjectName);
136 if (childObjectType == null) {
137 // Should not happen as child object is defined in oxm model
139 throw new CrudException("", Status.NOT_FOUND);
141 return childObjectType.getDescriptor().getTableName();
143 return modelObjectType.getDescriptor().getTableName();
148 public static Vertex validateIncomingUpsertPayload(String id, String version, String type, JsonElement properties)
149 throws CrudException {
152 type = resolveCollectionType(version, type);
153 DynamicJAXBContext jaxbContext = OxmModelLoader.getContextForVersion(version);
154 String modelObjectClass = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL,
155 CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, type));
157 final DynamicType modelObjectType = jaxbContext.getDynamicType(modelObjectClass);
158 final DynamicType reservedType = jaxbContext.getDynamicType("ReservedPropNames");
160 Set<Map.Entry<String, JsonElement>> payloadEntriesSet = properties.getAsJsonObject().entrySet();
162 // loop through input to validate against schema
163 for (Map.Entry<String, JsonElement> entry : payloadEntriesSet) {
164 String keyJavaName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, entry.getKey());
166 // check for valid field
167 if (modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName) == null) {
168 if (reservedType.getDescriptor().getMappingForAttributeName(keyJavaName) == null) {
169 throw new CrudException("Invalid field: " + entry.getKey(), Status.BAD_REQUEST);
175 Map<String, JsonElement> entriesMap = new HashMap<String, JsonElement>();
176 for (Map.Entry<String, JsonElement> entry : payloadEntriesSet) {
177 entriesMap.put(entry.getKey(), entry.getValue());
180 Vertex.Builder modelVertexBuilder = new Vertex.Builder(type);
182 modelVertexBuilder.id(id);
184 for (DatabaseMapping mapping : modelObjectType.getDescriptor().getMappings()) {
185 if (mapping.isAbstractDirectMapping()) {
186 DatabaseField field = mapping.getField();
187 String defaultValue = mapping.getProperties().get("defaultValue") == null ? ""
188 : mapping.getProperties().get("defaultValue").toString();
190 String keyName = field.getName().substring(0, field.getName().indexOf("/"));
192 if (((XMLField) field).isRequired() && !entriesMap.containsKey(keyName) && !defaultValue.isEmpty()) {
193 modelVertexBuilder.property(keyName, CrudServiceUtil.validateFieldType(defaultValue, field.getType()));
195 // if schema field is required and not set then reject
196 if (((XMLField) field).isRequired() && !entriesMap.containsKey(keyName) && defaultValue.isEmpty()) {
197 throw new CrudException("Missing required field: " + keyName, Status.BAD_REQUEST);
199 // If invalid field then reject
200 if (entriesMap.containsKey(keyName)) {
201 Object value = CrudServiceUtil.validateFieldType(entriesMap.get(keyName).getAsString(), field.getType());
202 modelVertexBuilder.property(keyName, value);
206 if (!defaultValue.isEmpty() && !entriesMap.containsKey(keyName)) {
207 modelVertexBuilder.property(keyName, CrudServiceUtil.validateFieldType(defaultValue, field.getType()));
212 // Handle reserved properties
213 for (DatabaseMapping mapping : reservedType.getDescriptor().getMappings()) {
214 if (mapping.isAbstractDirectMapping()) {
215 DatabaseField field = mapping.getField();
216 String keyName = field.getName().substring(0, field.getName().indexOf("/"));
218 if (entriesMap.containsKey(keyName)) {
219 Object value = CrudServiceUtil.validateFieldType(entriesMap.get(keyName).getAsString(), field.getType());
220 modelVertexBuilder.property(keyName, value);
225 return modelVertexBuilder.build();
226 } catch (Exception e) {
227 throw new CrudException(e.getMessage(), Status.BAD_REQUEST);
231 public static Vertex validateIncomingPatchPayload(String id, String version, String type, JsonElement properties,
232 Vertex existingVertex) throws CrudException {
234 type = resolveCollectionType(version, type);
235 DynamicJAXBContext jaxbContext = OxmModelLoader.getContextForVersion(version);
236 String modelObjectClass = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL,
237 CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, type));
239 final DynamicType modelObjectType = jaxbContext.getDynamicType(modelObjectClass);
240 final DynamicType reservedType = jaxbContext.getDynamicType("ReservedPropNames");
242 Set<Map.Entry<String, JsonElement>> payloadEntriesSet = properties.getAsJsonObject().entrySet();
244 // Loop through the payload properties and merge with existing
246 for (Map.Entry<String, JsonElement> entry : payloadEntriesSet) {
248 String keyJavaName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, entry.getKey());
250 DatabaseField field = null;
251 String defaultValue = null;
253 if (modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName) != null) {
254 field = modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName).getField();
255 defaultValue = modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName).getProperties()
256 .get("defaultValue") == null ? ""
257 : modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName).getProperties()
258 .get("defaultValue").toString();
259 } else if (reservedType.getDescriptor().getMappingForAttributeName(keyJavaName) != null) {
260 field = reservedType.getDescriptor().getMappingForAttributeName(keyJavaName).getField();
265 throw new CrudException("Invalid field: " + entry.getKey(), Status.BAD_REQUEST);
268 // check if mandatory field is not set to null
269 if (((XMLField) field).isRequired() && entry.getValue() instanceof JsonNull && !defaultValue.isEmpty()) {
270 existingVertex.getProperties().put(entry.getKey(),
271 CrudServiceUtil.validateFieldType(defaultValue, field.getType()));
272 } else if (((XMLField) field).isRequired() && entry.getValue() instanceof JsonNull && defaultValue.isEmpty()) {
273 throw new CrudException("Mandatory field: " + entry.getKey() + " can't be set to null", Status.BAD_REQUEST);
274 } else if (!((XMLField) field).isRequired() && entry.getValue() instanceof JsonNull
275 && existingVertex.getProperties().containsKey(entry.getKey())) {
276 existingVertex.getProperties().remove(entry.getKey());
277 } else if (!(entry.getValue() instanceof JsonNull)) {
278 // add/update the value if found in existing vertex
279 Object value = CrudServiceUtil.validateFieldType(entry.getValue().getAsString(), field.getType());
280 existingVertex.getProperties().put(entry.getKey(), value);
284 return existingVertex;
285 } catch (Exception e) {
286 throw new CrudException(e.getMessage(), Status.BAD_REQUEST);
290 private static DatabaseField getDatabaseField(String fieldName, DynamicType modelObjectType) {
291 for (DatabaseField field : modelObjectType.getDescriptor().getAllFields()) {
292 int ix = field.getName().indexOf("/");
294 ix = field.getName().length();
297 String keyName = field.getName().substring(0, ix);
298 if (fieldName.equals(keyName)) {
305 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));
325 return modelVertexBuilder.build();
326 } catch (Exception ex) {