Apply multiplicity Rule upon Edge creation
[aai/gizmo.git] / src / main / java / org / onap / crud / entity / Vertex.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
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
11  *
12  *       http://www.apache.org/licenses/LICENSE-2.0
13  *
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=========================================================
20  */
21 package org.onap.crud.entity;
22
23 import java.util.ArrayList;
24 import java.util.HashMap;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.Optional;
28 import org.eclipse.persistence.dynamic.DynamicType;
29 import org.eclipse.persistence.internal.helper.DatabaseField;
30 import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext;
31 import org.eclipse.persistence.mappings.DatabaseMapping;
32 import org.json.JSONArray;
33 import org.json.JSONObject;
34 import org.onap.crud.exception.CrudException;
35 import org.onap.crud.util.CrudServiceUtil;
36 import org.onap.schema.OxmModelLoader;
37 import org.onap.schema.validation.OxmModelValidator;
38 import com.google.common.base.CaseFormat;
39 import com.google.gson.Gson;
40 import com.google.gson.GsonBuilder;
41 import com.google.gson.annotations.SerializedName;
42 import net.dongliu.gson.GsonJava8TypeAdapterFactory;
43
44 public class Vertex {
45   private static final Gson gson = new GsonBuilder().registerTypeAdapterFactory(new GsonJava8TypeAdapterFactory())
46       .create();
47
48   @SerializedName(value = "id", alternate = { "key" })
49   private final Optional<String> id;
50
51   private final String type;
52   private final Map<String, Object> properties;
53
54   private Vertex(Builder builder) {
55     this.id = builder.id;
56     this.type = builder.type;
57     this.properties = builder.properties;
58   }
59
60   public static class Builder {
61     private Optional<String> id = Optional.empty();
62     private final String type;
63     private final Map<String, Object> properties = new HashMap<String, Object>();
64
65     public Builder(String type) {
66       if (type == null) {
67         throw new IllegalArgumentException("Type cannot be null");
68       }
69       this.type = type;
70     }
71
72     public Builder id(String id) {
73       if (id == null) {
74         throw new IllegalArgumentException("id cannot be null");
75       }
76
77       this.id = Optional.of(id);
78       return this;
79     }
80
81     public Builder property(String key, Object value) {
82       if (key == null || value == null) {
83         throw new IllegalArgumentException("Property key/value cannot be null");
84       }
85       properties.put(key, value);
86       return this;
87     }
88
89     public Vertex build() {
90       return new Vertex(this);
91     }
92   }
93
94   public String toJson() {
95     return gson.toJson(this);
96   }
97
98   public String toJson(Gson customGson) {
99     return customGson.toJson(this);
100   }
101
102   public static Vertex fromJson(String jsonString, String version) throws CrudException {
103     JSONObject doc = new JSONObject(jsonString);
104     return fromJson(doc, version);
105   }
106
107   public static Vertex fromJson(JSONObject jsonObject, String version) throws CrudException {
108     Builder builder;
109
110     try {
111       String type = jsonObject.getString("type");
112       builder = new Builder(type).id(jsonObject.getString("key"));
113
114       type = OxmModelValidator.resolveCollectionType(version, type);
115       DynamicJAXBContext jaxbContext = OxmModelLoader.getContextForVersion(version);
116       String modelObjectClass = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, type));
117
118       final DynamicType modelObjectType = jaxbContext.getDynamicType(modelObjectClass);
119       final DynamicType reservedType = jaxbContext.getDynamicType("ReservedPropNames");
120
121
122       if (modelObjectType == null) {
123         throw new CrudException("Unable to load oxm version", javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR);
124       }
125
126       if (jsonObject.has("properties")) {
127         JSONObject jsonProps = jsonObject.getJSONObject("properties");
128         for (String key : jsonProps.keySet()) {
129           String keyJavaName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, key);
130           DatabaseMapping mapping = modelObjectType.getDescriptor().getMappingForAttributeName(keyJavaName);
131
132           if (mapping == null) {
133             // This might be one of the reserved properties
134             mapping = reservedType.getDescriptor().getMappingForAttributeName(keyJavaName);
135           }
136
137           if (mapping != null) {
138             DatabaseField field = mapping.getField();
139             Object value = CrudServiceUtil.validateFieldType(jsonProps.get(key).toString(), field.getType());
140             builder.property(key, value);
141           }
142         }
143       }
144     }
145     catch (Exception ex) {
146       throw new CrudException("Unable to transform response: " + jsonObject.toString(), javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR);
147     }
148
149     return builder.build();
150   }
151
152   public static List<Vertex> collectionFromJson(String jsonString, String version) throws CrudException {
153     List<Vertex> result = new ArrayList<>();
154     JSONArray array = new JSONArray(jsonString);
155
156     for (Object jsonObject : array) {
157       result.add(Vertex.fromJson((JSONObject)jsonObject, version));
158     }
159
160     return result;
161   }
162
163   @Override
164   public String toString() {
165     return "Vertex [id=" + id + ", type=" + type + ", properties=" + properties + "]";
166   }
167
168   public Optional<String> getId() {
169     return id;
170   }
171
172   public String getType() {
173     return type;
174   }
175
176   public Map<String, Object> getProperties() {
177     return properties;
178   }
179
180 }