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