Initial commit for AAI-UI(sparky-backend)
[aai/sparky-be.git] / src / main / java / org / openecomp / sparky / inventory / entity / GeoIndexDocument.java
1 /**
2  * ============LICENSE_START===================================================
3  * SPARKY (AAI UI service)
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 and OpenECOMP are trademarks
23  * and service marks of AT&T Intellectual Property.
24  */
25
26 package org.openecomp.sparky.inventory.entity;
27
28 import com.fasterxml.jackson.databind.ObjectMapper;
29 import com.fasterxml.jackson.databind.node.ObjectNode;
30
31 import java.io.Serializable;
32 import java.security.MessageDigest;
33 import java.security.NoSuchAlgorithmException;
34 import java.util.List;
35
36 import javax.json.Json;
37 import javax.json.JsonObject;
38
39 import org.openecomp.sparky.config.oxm.OxmEntityDescriptor;
40 import org.openecomp.sparky.config.oxm.OxmModelLoader;
41 import org.openecomp.sparky.synchronizer.entity.IndexDocument;
42 import org.openecomp.sparky.util.NodeUtils;
43
44 /**
45  * The Class GeoIndexDocument.
46  */
47 public class GeoIndexDocument implements Serializable, IndexDocument {
48
49   private static final long serialVersionUID = -5188479658230319058L;
50
51   protected String entityType;
52   protected String entityPrimaryKeyValue;
53   protected String entityPrimaryKeyName;
54   protected String latitude;
55   protected String longitude;
56   protected String selfLink;
57   protected OxmModelLoader loader;
58   protected ObjectMapper mapper = new ObjectMapper();
59   // generated, SHA-256 digest
60   protected String id;
61
62   /**
63    * Instantiates a new geo index document.
64    *
65    * @param loader the loader
66    */
67   public GeoIndexDocument(OxmModelLoader loader) {
68     this();
69     this.loader = loader;
70   }
71
72   /**
73    * Convert bytes to hex string.
74    *
75    * @param bytesToConvert the bytes to convert
76    * @return the string
77    */
78   private static String convertBytesToHexString(byte[] bytesToConvert) {
79     StringBuffer hexString = new StringBuffer();
80     for (int i = 0; i < bytesToConvert.length; i++) {
81       hexString.append(Integer.toHexString(0xFF & bytesToConvert[i]));
82     }
83     return hexString.toString();
84   }
85
86
87
88   public boolean isValidGeoDocument() {
89
90     boolean isValid = true;
91
92     isValid &= (this.getEntityType() != null);
93     isValid &= (this.getLatitude() != null);
94     isValid &= (this.getLongitude() != null);
95     isValid &= (this.getId() != null);
96     isValid &= (this.getSelfLink() != null);
97
98     isValid &= NodeUtils.isNumeric(this.getLatitude());
99     isValid &= NodeUtils.isNumeric(this.getLongitude());
100
101     return isValid;
102   }
103
104   /**
105    * Concat array.
106    *
107    * @param list the list
108    * @param delimiter the delimiter
109    * @return the string
110    */
111   private static String concatArray(List<String> list, char delimiter) {
112
113     if (list == null || list.size() == 0) {
114       return "";
115     }
116
117     StringBuilder result = new StringBuilder(64);
118
119     int listSize = list.size();
120     boolean firstValue = true;
121
122     for (String item : list) {
123
124       if (firstValue) {
125         result.append(item);
126         firstValue = false;
127       } else {
128         result.append(delimiter).append(item);
129       }
130
131     }
132
133     return result.toString();
134
135   }
136
137   /*
138    * We'll try and create a unique identity key that we can use for differencing the previously
139    * imported record sets as we won't have granular control of what is created/removed and when. The
140    * best we can hope for is identification of resources by generated Id until the Identity-Service
141    * UUID is tagged against all resources, then we can use that instead.
142    */
143
144   /**
145    * Generate unique sha digest.
146    *
147    * @param entityType the entity type
148    * @param fieldName the field name
149    * @param fieldValue the field value
150    * @return the string
151    * @throws NoSuchAlgorithmException the no such algorithm exception
152    */
153   public static String generateUniqueShaDigest(String entityType, String fieldName,
154       String fieldValue) throws NoSuchAlgorithmException {
155
156     /*
157      * Basically SHA-256 will result in an identity with a guaranteed uniqueness compared to just a
158      * java hashcode value.
159      */
160     MessageDigest digest = MessageDigest.getInstance("SHA-256");
161     digest.update(String.format("%s.%s.%s", entityType, fieldName, fieldValue).getBytes());
162     return convertBytesToHexString(digest.digest());
163   }
164
165   /**
166    * Instantiates a new geo index document.
167    */
168   public GeoIndexDocument() {}
169
170   /*
171    * (non-Javadoc)
172    * 
173    * @see com.att.queryrouter.dao.DocumentStoreDataEntity#getAsJson()
174    */
175   @Override
176   public String getIndexDocumentJson() {
177
178     JsonObject obj = null;
179
180     if (latitude != null && longitude != null) {
181       obj =
182           Json.createObjectBuilder().add("entityType", entityType)
183               .add("pkey", entityPrimaryKeyValue)
184               .add("location",
185                   Json.createObjectBuilder().add("lat", latitude).add("lon", longitude))
186           .add("selfLink", selfLink).build();
187
188     } else {
189       obj = Json.createObjectBuilder().add("entityType", entityType)
190           .add("pkey", entityPrimaryKeyValue).add("selfLink", selfLink).build();
191     }
192
193     return obj.toString();
194   }
195
196   /* (non-Javadoc)
197    * @see org.openecomp.sparky.synchronizer.entity.IndexDocument#deriveFields()
198    */
199   @Override
200   public void deriveFields() {
201
202     /*
203      * We'll try and create a unique identity key that we can use for differencing the previously
204      * imported record sets as we won't have granular control of what is created/removed and when.
205      * The best we can hope for is identification of resources by generated Id until the
206      * Identity-Service UUID is tagged against all resources, then we can use that instead.
207      */
208
209     OxmEntityDescriptor descriptor = loader.getEntityDescriptor(entityType);
210     String entityPrimaryKeyName = NodeUtils.concatArray(
211         descriptor.getPrimaryKeyAttributeName(), "/");
212
213     this.id =
214         NodeUtils.generateUniqueShaDigest(entityType, entityPrimaryKeyName, entityPrimaryKeyValue);
215   }
216
217   /* (non-Javadoc)
218    * @see java.lang.Object#toString()
219    */
220   @Override
221   public String toString() {
222     return "TopographicalEntity [" + ("entityType=" + entityType + ", ")
223         + ("entityPrimaryKeyValue=" + entityPrimaryKeyValue + ", ")
224         + ("latitude=" + latitude + ", ") + ("longitude=" + longitude + ", ") + ("ID=" + id + ", ")
225         + ("selfLink=" + selfLink) + "]";
226   }
227
228   @Override
229   public String getId() {
230     return this.id;
231   }
232
233   public String getEntityType() {
234     return entityType;
235   }
236
237   public void setEntityType(String entityType) {
238     this.entityType = entityType;
239   }
240
241   public String getEntityPrimaryKeyValue() {
242     return entityPrimaryKeyValue;
243   }
244
245   public void setEntityPrimaryKeyValue(String entityPrimaryKeyValue) {
246     this.entityPrimaryKeyValue = entityPrimaryKeyValue;
247   }
248
249   public String getEntityPrimaryKeyName() {
250     return entityPrimaryKeyName;
251   }
252
253   public void setEntityPrimaryKeyName(String entityPrimaryKeyName) {
254     this.entityPrimaryKeyName = entityPrimaryKeyName;
255   }
256
257   public String getLatitude() {
258     return latitude;
259   }
260
261   public void setLatitude(String latitude) {
262     this.latitude = latitude;
263   }
264
265   public String getLongitude() {
266     return longitude;
267   }
268
269   public void setLongitude(String longitude) {
270     this.longitude = longitude;
271   }
272
273   public String getSelfLink() {
274     return selfLink;
275   }
276
277   public void setSelfLink(String selfLink) {
278     this.selfLink = selfLink;
279   }
280
281   public static long getSerialversionuid() {
282     return serialVersionUID;
283   }
284
285   public void setId(String id) {
286     this.id = id;
287   }
288
289   @Override
290   public ObjectNode getBulkImportEntity() {
291     // TODO Auto-generated method stub
292     return buildImportDataObject(this.entityType, this.entityPrimaryKeyValue, this.selfLink,
293         this.latitude, this.longitude);
294   }
295
296   /**
297    * Builds the import data object.
298    *
299    * @param entityType the entity type
300    * @param entityPrimaryKeyValue the entity primary key value
301    * @param selfLink the self link
302    * @param latitude the latitude
303    * @param longitude the longitude
304    * @return the object node
305    */
306   @SuppressWarnings("deprecation")
307   protected ObjectNode buildImportDataObject(String entityType, String entityPrimaryKeyValue,
308       String selfLink, String latitude, String longitude) {
309     ObjectNode childNode = mapper.createObjectNode();
310     childNode.put("lat", latitude);
311     childNode.put("lon", longitude);
312     ObjectNode parentNode = mapper.createObjectNode();
313
314     parentNode.put("entityType", entityType);
315     parentNode.put("pkey", entityPrimaryKeyValue);
316     parentNode.put("selfLink", selfLink);
317     parentNode.put("location", childNode);
318
319     return parentNode;
320   }
321
322 }