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);
167 Set<Map.Entry<String, JsonElement>> payloadEntriesSet = properties.getAsJsonObject()
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 throw new CrudException("Invalid field: " + entry.getKey(), Status.BAD_REQUEST);
181 Map<String, JsonElement> entriesMap = new HashMap<String, JsonElement>();
182 for (Map.Entry<String, JsonElement> entry : payloadEntriesSet) {
183 entriesMap.put(entry.getKey(), entry.getValue());
186 Vertex.Builder modelVertexBuilder = new Vertex.Builder(type);
188 modelVertexBuilder.id(id);
190 for (DatabaseMapping mapping : modelObjectType.getDescriptor().getMappings()) {
191 if (mapping.isAbstractDirectMapping()) {
192 DatabaseField field = mapping.getField();
193 String defaultValue = mapping.getProperties().get("defaultValue") == null ? ""
194 : mapping.getProperties().get("defaultValue").toString();
196 String keyName = field.getName().substring(0, field.getName().indexOf("/"));
198 if (((XMLField) field).isRequired() && !entriesMap.containsKey(keyName)
199 && !defaultValue.isEmpty()) {
200 modelVertexBuilder.property(keyName,
201 CrudServiceUtil.validateFieldType(defaultValue, field.getType()));
203 // if schema field is required and not set then reject
204 if (((XMLField) field).isRequired() && !entriesMap.containsKey(keyName)
205 && defaultValue.isEmpty()) {
206 throw new CrudException("Missing required field: " + keyName, Status.BAD_REQUEST);
208 // If invalid field then reject
209 if (entriesMap.containsKey(keyName)) {
210 Object value = CrudServiceUtil.validateFieldType(entriesMap.get(keyName)
211 .getAsString(), field.getType());
212 modelVertexBuilder.property(keyName, value);
216 if (!defaultValue.isEmpty() && !entriesMap.containsKey(keyName)) {
217 modelVertexBuilder.property(keyName,
218 CrudServiceUtil.validateFieldType(defaultValue, field.getType()));
223 return modelVertexBuilder.build();
224 } catch (Exception e) {
225 throw new CrudException(e.getMessage(), Status.BAD_REQUEST);
229 public static Vertex validateIncomingPatchPayload(String id, String version, String type,
230 JsonElement properties, Vertex existingVertex)
231 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);
241 Set<Map.Entry<String, JsonElement>> payloadEntriesSet = properties.getAsJsonObject()
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 // check for valid field
251 if (modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName) == null) {
252 throw new CrudException("Invalid field: " + entry.getKey(), Status.BAD_REQUEST);
255 DatabaseField field = modelObjectType.getDescriptor()
256 .getMappingForAttributeName(keyJavaName).getField();
257 String defaultValue = modelObjectType.getDescriptor()
258 .getMappingForAttributeName(keyJavaName)
259 .getProperties().get("defaultValue") == null ? ""
260 : modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName)
261 .getProperties().get("defaultValue").toString();
263 // check if mandatory field is not set to null
264 if (((XMLField) field).isRequired() && entry.getValue() instanceof JsonNull
265 && !defaultValue.isEmpty()) {
266 existingVertex.getProperties().put(entry.getKey(),
267 CrudServiceUtil.validateFieldType(defaultValue, field.getType()));
268 } else if (((XMLField) field).isRequired() && entry.getValue() instanceof JsonNull
269 && defaultValue.isEmpty()) {
270 throw new CrudException("Mandatory field: " + entry.getKey()
271 + " can't be set to null",
273 } else if (!((XMLField) field).isRequired() && entry.getValue() instanceof JsonNull
274 && existingVertex.getProperties().containsKey(entry.getKey())) {
275 existingVertex.getProperties().remove(entry.getKey());
276 } else if (!(entry.getValue() instanceof JsonNull)) {
277 // add/update the value if found in existing vertex
278 Object value = CrudServiceUtil.validateFieldType(entry.getValue().getAsString(),
280 existingVertex.getProperties().put(entry.getKey(), value);
285 return existingVertex;
286 } catch (Exception e) {
287 throw new CrudException(e.getMessage(), Status.BAD_REQUEST);
292 private static DatabaseField getDatabaseField(String fieldName, DynamicType modelObjectType) {
293 for (DatabaseField field : modelObjectType.getDescriptor().getAllFields()) {
294 int ix = field.getName().indexOf("/");
296 ix = field.getName().length();
299 String keyName = field.getName().substring(0, ix);
300 if (fieldName.equals(keyName)) {
307 public static Vertex validateOutgoingPayload(String version, Vertex vertex) {
309 Vertex.Builder modelVertexBuilder = new Vertex.Builder(vertex.getType())
310 .id(vertex.getId().get());
313 DynamicJAXBContext jaxbContext = OxmModelLoader.getContextForVersion(version);
314 String modelObjectClass = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL,
315 CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL,
316 vertex.getProperties().get(Metadata.NODE_TYPE.propertyName()) != null
317 ? vertex.getProperties().get(Metadata.NODE_TYPE.propertyName()).toString() : vertex.getType()));
318 final DynamicType modelObjectType = jaxbContext.getDynamicType(modelObjectClass);
320 for (String key : vertex.getProperties().keySet()) {
321 DatabaseField field = getDatabaseField(key, modelObjectType);
323 if (!Metadata.isProperty(key)) {
324 modelVertexBuilder.property(key, vertex.getProperties().get(key));
328 return modelVertexBuilder.build();
329 } catch (Exception ex) {