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