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