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.openecomp.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.openecomp.crud.entity.Vertex;
37 import org.openecomp.crud.exception.CrudException;
38 import org.openecomp.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 SOT("source-of-truth"),
51 LAST_MOD_SOT("last-mod-source-of-truth");
53 private final String propName;
55 Metadata(String propName) {
56 this.propName = propName;
59 public String propertyName() {
63 public static boolean isProperty(String property) {
64 for (Metadata meta : Metadata.values()) {
65 if (meta.propName.equals(property)) {
74 public static Map<String, Object> resolveCollectionfilter(String version, String type,
75 Map<String, String> filter)
76 throws CrudException {
78 DynamicJAXBContext jaxbContext = null;
80 jaxbContext = OxmModelLoader.getContextForVersion(version);
81 } catch (Exception e) {
82 throw new CrudException(e);
85 Map<String, Object> result = new HashMap<String, Object>();
86 if (jaxbContext == null) {
87 throw new CrudException("", Status.NOT_FOUND);
89 final DynamicType modelObjectType = jaxbContext.getDynamicType(CaseFormat.LOWER_CAMEL
90 .to(CaseFormat.UPPER_CAMEL,
91 CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, type)));
93 for (String key : filter.keySet()) {
94 String keyJavaName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, key);
95 if (modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName) != null) {
97 DatabaseMapping mapping = modelObjectType.getDescriptor()
98 .getMappingForAttributeName(keyJavaName);
99 Object value = CrudServiceUtil.validateFieldType(filter.get(key),
100 mapping.getField().getType());
101 result.put(key, value);
102 } catch (Exception ex) {
103 // Skip any exceptions thrown while validating the filter
114 public static String resolveCollectionType(String version, String type) throws CrudException {
116 DynamicJAXBContext jaxbContext = null;
118 jaxbContext = OxmModelLoader.getContextForVersion(version);
119 } catch (Exception e) {
120 throw new CrudException(e);
123 if (jaxbContext == null) {
124 throw new CrudException("", Status.NOT_FOUND);
126 // Determine if the Object part is a collection type in the model
128 final DynamicType modelObjectType = jaxbContext.getDynamicType(CaseFormat.LOWER_CAMEL
129 .to(CaseFormat.UPPER_CAMEL,
130 CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, type)));
132 if (modelObjectType == null) {
133 throw new CrudException("", Status.NOT_FOUND);
136 if (modelObjectType.getDescriptor().getMappings().size() == 1
137 && modelObjectType.getDescriptor().getMappings().get(0).isCollectionMapping()) {
138 String childJavaObjectName = modelObjectType.getDescriptor().getMappings()
139 .get(0).getAttributeName();
140 childJavaObjectName = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, childJavaObjectName);
141 final DynamicType childObjectType = jaxbContext.getDynamicType(childJavaObjectName);
142 if (childObjectType == null) {
143 // Should not happen as child object is defined in oxm model
145 throw new CrudException("", Status.NOT_FOUND);
147 return childObjectType.getDescriptor().getTableName();
149 return modelObjectType.getDescriptor().getTableName();
155 public static Vertex validateIncomingUpsertPayload(String id, String version, String type,
156 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()
171 //loop through input to validate against schema
172 for (Map.Entry<String, JsonElement> entry : payloadEntriesSet) {
173 String keyJavaName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, entry.getKey());
175 // check for valid field
176 if (modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName) == null) {
177 if(reservedType.getDescriptor().getMappingForAttributeName(keyJavaName) == null){
178 throw new CrudException("Invalid field: " + entry.getKey(), Status.BAD_REQUEST);
184 Map<String, JsonElement> entriesMap = new HashMap<String, JsonElement>();
185 for (Map.Entry<String, JsonElement> entry : payloadEntriesSet) {
186 entriesMap.put(entry.getKey(), entry.getValue());
189 Vertex.Builder modelVertexBuilder = new Vertex.Builder(type);
191 modelVertexBuilder.id(id);
193 for (DatabaseMapping mapping : modelObjectType.getDescriptor().getMappings()) {
194 if (mapping.isAbstractDirectMapping()) {
195 DatabaseField field = mapping.getField();
196 String defaultValue = mapping.getProperties().get("defaultValue") == null ? ""
197 : mapping.getProperties().get("defaultValue").toString();
199 String keyName = field.getName().substring(0, field.getName().indexOf("/"));
201 if (((XMLField) field).isRequired() && !entriesMap.containsKey(keyName)
202 && !defaultValue.isEmpty()) {
203 modelVertexBuilder.property(keyName,
204 CrudServiceUtil.validateFieldType(defaultValue, field.getType()));
206 // if schema field is required and not set then reject
207 if (((XMLField) field).isRequired() && !entriesMap.containsKey(keyName)
208 && defaultValue.isEmpty()) {
209 throw new CrudException("Missing required field: " + keyName, Status.BAD_REQUEST);
211 // If invalid field then reject
212 if (entriesMap.containsKey(keyName)) {
213 Object value = CrudServiceUtil.validateFieldType(entriesMap.get(keyName)
214 .getAsString(), field.getType());
215 modelVertexBuilder.property(keyName, value);
219 if (!defaultValue.isEmpty() && !entriesMap.containsKey(keyName)) {
220 modelVertexBuilder.property(keyName,
221 CrudServiceUtil.validateFieldType(defaultValue, field.getType()));
226 // Handle reserved properties
227 for (DatabaseMapping mapping : reservedType.getDescriptor().getMappings()) {
228 if (mapping.isAbstractDirectMapping()) {
229 DatabaseField field = mapping.getField();
230 String keyName = field.getName().substring(0, field.getName().indexOf("/"));
232 if (entriesMap.containsKey(keyName)) {
233 Object value = CrudServiceUtil.validateFieldType(entriesMap.get(keyName)
234 .getAsString(), field.getType());
235 modelVertexBuilder.property(keyName, value);
240 return modelVertexBuilder.build();
241 } catch (Exception e) {
242 throw new CrudException(e.getMessage(), Status.BAD_REQUEST);
246 public static Vertex validateIncomingPatchPayload(String id, String version, String type,
247 JsonElement properties, Vertex existingVertex)
248 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()
262 // Loop through the payload properties and merge with existing
264 for (Map.Entry<String, JsonElement> entry : payloadEntriesSet) {
266 String keyJavaName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, entry.getKey());
268 DatabaseField field = null;
269 String defaultValue = null;
271 if (modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName) != null) {
272 field = modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName).getField();
273 defaultValue = modelObjectType.getDescriptor()
274 .getMappingForAttributeName(keyJavaName)
275 .getProperties().get("defaultValue") == null ? ""
276 : modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName)
277 .getProperties().get("defaultValue").toString();
279 else if (reservedType.getDescriptor().getMappingForAttributeName(keyJavaName) != null) {
280 field = reservedType.getDescriptor().getMappingForAttributeName(keyJavaName).getField();
285 throw new CrudException("Invalid field: " + entry.getKey(), Status.BAD_REQUEST);
288 // check if mandatory field is not set to null
289 if (((XMLField) field).isRequired() && entry.getValue() instanceof JsonNull
290 && !defaultValue.isEmpty()) {
291 existingVertex.getProperties().put(entry.getKey(),
292 CrudServiceUtil.validateFieldType(defaultValue, field.getType()));
293 } else if (((XMLField) field).isRequired() && entry.getValue() instanceof JsonNull
294 && defaultValue.isEmpty()) {
295 throw new CrudException("Mandatory field: " + entry.getKey()
296 + " can't be set to null",
298 } else if (!((XMLField) field).isRequired() && entry.getValue() instanceof JsonNull
299 && existingVertex.getProperties().containsKey(entry.getKey())) {
300 existingVertex.getProperties().remove(entry.getKey());
301 } else if (!(entry.getValue() instanceof JsonNull)) {
302 // add/update the value if found in existing vertex
303 Object value = CrudServiceUtil.validateFieldType(entry.getValue().getAsString(),
305 existingVertex.getProperties().put(entry.getKey(), value);
310 return existingVertex;
311 } catch (Exception e) {
312 throw new CrudException(e.getMessage(), Status.BAD_REQUEST);
317 private static DatabaseField getDatabaseField(String fieldName, DynamicType modelObjectType) {
318 for (DatabaseField field : modelObjectType.getDescriptor().getAllFields()) {
319 int ix = field.getName().indexOf("/");
321 ix = field.getName().length();
324 String keyName = field.getName().substring(0, ix);
325 if (fieldName.equals(keyName)) {
332 public static Vertex validateOutgoingPayload(String version, Vertex vertex) {
334 Vertex.Builder modelVertexBuilder = new Vertex.Builder(vertex.getType())
335 .id(vertex.getId().get());
338 DynamicJAXBContext jaxbContext = OxmModelLoader.getContextForVersion(version);
339 String modelObjectClass = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL,
340 CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL,
341 vertex.getProperties().get(Metadata.NODE_TYPE.propertyName()) != null
342 ? vertex.getProperties().get(Metadata.NODE_TYPE.propertyName()).toString() : vertex.getType()));
343 final DynamicType modelObjectType = jaxbContext.getDynamicType(modelObjectClass);
345 for (String key : vertex.getProperties().keySet()) {
346 DatabaseField field = getDatabaseField(key, modelObjectType);
348 if (!Metadata.isProperty(key)) {
349 modelVertexBuilder.property(key, vertex.getProperties().get(key));
353 return modelVertexBuilder.build();
354 } catch (Exception ex) {