summaryrefslogtreecommitdiffstats
path: root/sparkybe-onap-service/src/main/java/org/onap/aai/sparky/viewandinspect/services/BaseVisualizationContext.java
blob: aa4508caef0279635e81f65661b7ccd8a7ad5a47 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
/**
 * ============LICENSE_START=======================================================
 * org.onap.aai
 * ================================================================================
 * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
 * Copyright © 2017-2018 Amdocs
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */
package org.onap.aai.sparky.viewandinspect.services;

import static java.util.concurrent.CompletableFuture.supplyAsync;

import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.http.client.utils.URIBuilder;
import org.onap.aai.cl.api.Logger;
import org.onap.aai.cl.eelf.LoggerFactory;
import org.onap.aai.restclient.client.OperationResult;
import org.onap.aai.sparky.config.oxm.OxmEntityDescriptor;
import org.onap.aai.sparky.config.oxm.OxmEntityLookup;
import org.onap.aai.sparky.dal.ActiveInventoryAdapter;
import org.onap.aai.sparky.logging.AaiUiMsgs;
import org.onap.aai.sparky.sync.entity.SearchableEntity;
import org.onap.aai.sparky.util.NodeUtils;
import org.onap.aai.sparky.viewandinspect.config.SparkyConstants;
import org.onap.aai.sparky.viewandinspect.config.VisualizationConfigs;
import org.onap.aai.sparky.viewandinspect.entity.ActiveInventoryNode;
import org.onap.aai.sparky.viewandinspect.entity.InlineMessage;
import org.onap.aai.sparky.viewandinspect.entity.NodeProcessingTransaction;
import org.onap.aai.sparky.viewandinspect.entity.QueryParams;
import org.onap.aai.sparky.viewandinspect.entity.Relationship;
import org.onap.aai.sparky.viewandinspect.entity.RelationshipData;
import org.onap.aai.sparky.viewandinspect.entity.RelationshipList;
import org.onap.aai.sparky.viewandinspect.entity.SelfLinkDeterminationTransaction;
import org.onap.aai.sparky.viewandinspect.enumeration.NodeProcessingAction;
import org.onap.aai.sparky.viewandinspect.enumeration.NodeProcessingState;
import org.onap.aai.sparky.viewandinspect.task.PerformNodeSelfLinkProcessingTask;
import org.onap.aai.sparky.viewandinspect.task.PerformSelfLinkDeterminationTask;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;

/** 
 * The Class SelfLinkNodeCollector.
 */
public class BaseVisualizationContext implements VisualizationContext {

  private static final int MAX_DEPTH_EVALUATION_ATTEMPTS = 100;
  private static final String DEPTH_ALL_MODIFIER = "?depth=all";
  private static final String NODES_ONLY_MODIFIER = "?nodes-only";
  private static final String SERVICE_INSTANCE = "service-instance";

  private static final Logger LOG = LoggerFactory.getInstance().getLogger(
      BaseVisualizationContext.class);
  private final ActiveInventoryAdapter aaiAdapter;

  private int maxSelfLinkTraversalDepth;
  private AtomicInteger numLinksDiscovered;
  private AtomicInteger numSuccessfulLinkResolveFromCache;
  private AtomicInteger numSuccessfulLinkResolveFromFromServer;
  private AtomicInteger numFailedLinkResolve;
  private AtomicInteger aaiWorkOnHand;
 
  private VisualizationConfigs visualizationConfigs;

  private AtomicInteger totalLinksRetrieved;

  private final long contextId;
  private final String contextIdStr;

  private ObjectMapper mapper;
  private InlineMessage inlineMessage = null;
  
  private ExecutorService aaiExecutorService;
  private OxmEntityLookup oxmEntityLookup;
  private boolean rootNodeFound;

  /*
   * The node cache is intended to be a flat structure indexed by a primary key to avoid needlessly
   * re-requesting the same self-links over-and-over again, to speed up the overall render time and
   * more importantly to reduce the network cost of determining information we already have.
   */
  private ConcurrentHashMap<String, ActiveInventoryNode> nodeCache;

  /**
   * Instantiates a new self link node collector.
   *
   * @param loader the loader
   * @throws Exception the exception
   */
  public BaseVisualizationContext(long contextId, ActiveInventoryAdapter aaiAdapter,
      ExecutorService aaiExecutorService, VisualizationConfigs visualizationConfigs,
      OxmEntityLookup oxmEntityLookup)
      throws Exception {
    
    this.contextId = contextId;
    this.contextIdStr = "[Context-Id=" + contextId + "]";
    this.aaiAdapter = aaiAdapter;
    this.aaiExecutorService = aaiExecutorService;
    this.visualizationConfigs = visualizationConfigs;
    this.oxmEntityLookup = oxmEntityLookup;
    
    this.nodeCache = new ConcurrentHashMap<String, ActiveInventoryNode>();
    this.numLinksDiscovered = new AtomicInteger(0);
    this.totalLinksRetrieved = new AtomicInteger(0);
    this.numSuccessfulLinkResolveFromCache = new AtomicInteger(0);
    this.numSuccessfulLinkResolveFromFromServer = new AtomicInteger(0);
    this.numFailedLinkResolve = new AtomicInteger(0);
    this.aaiWorkOnHand = new AtomicInteger(0);

    this.maxSelfLinkTraversalDepth = this.visualizationConfigs.getMaxSelfLinkTraversalDepth();

    this.mapper = new ObjectMapper();
    mapper.setSerializationInclusion(Include.NON_EMPTY);
    mapper.setPropertyNamingStrategy(new PropertyNamingStrategy.KebabCaseStrategy());
    this.rootNodeFound = false;
  }
  
  protected boolean isRootNodeFound() {
    return rootNodeFound;
  }

  protected void setRootNodeFound(boolean rootNodeFound) {
    this.rootNodeFound = rootNodeFound;
  }

  public long getContextId() {
    return contextId;
  }

  /**
   * A utility method for extracting all entity-type primary key values from a provided self-link
   * and return a set of generic-query API keys.
   * 
   * @param parentEntityType
   * @param link
   * @return a list of key values that can be used for this entity with the AAI generic-query API
   */
  protected List<String> extractQueryParamsFromSelfLink(String link) {

    List<String> queryParams = new ArrayList<String>();

    if (link == null) {
      LOG.error(AaiUiMsgs.QUERY_PARAM_EXTRACTION_ERROR, "self link is null");
      return queryParams;
    }

    Map<String, OxmEntityDescriptor> entityDescriptors = oxmEntityLookup.getEntityDescriptors();

    try {

      URIBuilder urlBuilder = new URIBuilder(link);
      String urlPath = urlBuilder.getPath();

      OxmEntityDescriptor descriptor = null;
      String[] urlPathElements = urlPath.split("/");
      List<String> primaryKeyNames = null;
      int index = 0;
      String entityType = null;

      while (index < urlPathElements.length) {

        descriptor = entityDescriptors.get(urlPathElements[index]);

        if (descriptor != null) {
          entityType = urlPathElements[index];
          primaryKeyNames = descriptor.getPrimaryKeyAttributeNames();

          /*
           * Make sure from what ever index we matched the parent entity-type on that we can extract
           * additional path elements for the primary key values.
           */

          if (index + primaryKeyNames.size() < urlPathElements.length) {

            for (String primaryKeyName : primaryKeyNames) {
              index++;
              queryParams.add(entityType + "." + primaryKeyName + ":" + urlPathElements[index]);
            }
          } else {
            LOG.error(AaiUiMsgs.QUERY_PARAM_EXTRACTION_ERROR,
                "Could not extract query parametrs for entity-type = '" + entityType
                    + "' from self-link = " + link);
          }
        }

        index++;
      }

    } catch (URISyntaxException exc) {

      LOG.error(AaiUiMsgs.QUERY_PARAM_EXTRACTION_ERROR,
          "Error extracting query parameters from self-link = " + link + ". Error = "
              + exc.getMessage());
    }

    return queryParams;

  }
  
  /**
   * Decode complex attribute group.
   *
   * @param ain the ain
   * @param attributeGroup the attribute group
   * @return boolean indicating whether operation was successful (true), / failure(false).
   */
  public boolean decodeComplexAttributeGroup(ActiveInventoryNode ain, JsonNode attributeGroup) {

    try {

      Iterator<Entry<String, JsonNode>> entityArrays = attributeGroup.fields();
      Entry<String, JsonNode> entityArray = null;

      if (entityArrays == null) {
        LOG.error(AaiUiMsgs.ATTRIBUTE_GROUP_FAILURE, attributeGroup.toString());
        ain.changeState(NodeProcessingState.ERROR, NodeProcessingAction.NEIGHBORS_PROCESSED_ERROR);
        return false;
      }

      while (entityArrays.hasNext()) {

        entityArray = entityArrays.next();

        String entityType = entityArray.getKey();
        JsonNode entityArrayObject = entityArray.getValue();

        if (entityArrayObject.isArray()) {

          Iterator<JsonNode> entityCollection = entityArrayObject.elements();
          JsonNode entity = null;
          while (entityCollection.hasNext()) {
            entity = entityCollection.next();

            if (LOG.isDebugEnabled()) {
              LOG.debug(AaiUiMsgs.DEBUG_GENERIC, "decodeComplexAttributeGroup(),"
                  + " entity = " + entity.toString());
            }

            /**
             * Here's what we are going to do:
             * 
             * <li>In the ActiveInventoryNode, on construction maintain a collection of queryParams
             * that is added to for the purpose of discovering parent->child hierarchies.
             * 
             * <li>When we hit this block of the code then we'll use the queryParams to feed the
             * generic query to resolve the self-link asynchronously.
             * 
             * <li>Upon successful link determination, then and only then will we create a new node
             * in the nodeCache and process the child
             * 
             */

            ActiveInventoryNode newNode = new ActiveInventoryNode(this.visualizationConfigs, oxmEntityLookup);
            newNode.setEntityType(entityType);

            /*
             * This is partially a lie because we actually don't have a self-link for complex nodes
             * discovered in this way.
             */
            newNode.setSelfLinkProcessed(true);
            newNode.changeState(NodeProcessingState.SELF_LINK_RESPONSE_UNPROCESSED,
                NodeProcessingAction.COMPLEX_ATTRIBUTE_GROUP_PARSE_OK);
            
            /*
             * copy parent query params into new child
             */
            
            if (SERVICE_INSTANCE.equals(entityType)) {
              
              /*
               * 1707 AAI has an issue being tracked with AAI-8932 where the generic-query cannot be
               * resolved if all the service-instance path keys are provided. The query only works
               * if only the service-instance key and valude are passed due to a historical reason.
               * A fix is being worked on for 1707, and when it becomes available we can revert this
               * small change.
               */
              
              newNode.clearQueryParams();
              
            } else {

              /*
               * For all other entity-types we want to copy the parent query parameters into the new node
               * query parameters.
               */

              for (String queryParam : ain.getQueryParams()) {
                newNode.addQueryParam(queryParam);
              }

            }
            
            
            if (!addComplexGroupToNode(newNode, entity)) {
              LOG.error(AaiUiMsgs.ATTRIBUTE_GROUP_FAILURE, "Failed to add child to parent for child = " +  entity.toString());
            }

            if (!addNodeQueryParams(newNode)) {
              LOG.error(AaiUiMsgs.FAILED_TO_DETERMINE_NODE_ID, "Error determining node id and key for node = " + newNode.dumpNodeTree(true)
                  + " skipping relationship processing");
              newNode.changeState(NodeProcessingState.ERROR,
                  NodeProcessingAction.NODE_IDENTITY_ERROR);
              return false;
            } else {

              newNode.changeState(NodeProcessingState.NEIGHBORS_UNPROCESSED,
                  NodeProcessingAction.COMPLEX_ATTRIBUTE_GROUP_PARSE_OK);

            }
            

            /*
             * Order matters for the query params. We need to set the parent ones before the child
             * node
             */

            String selfLinkQuery =
                aaiAdapter.getGenericQueryForSelfLink(entityType, newNode.getQueryParams());

            /**
             * <li>get the self-link
             * <li>add it to the new node
             * <li>generate node id
             * <li>add node to node cache
             * <li>add node id to parent outbound links list
             * <li>process node children (should be automatic) (but don't query and resolve
             * self-link as we already have all the data)
             */

            SelfLinkDeterminationTransaction txn = new SelfLinkDeterminationTransaction();

            txn.setQueryString(selfLinkQuery);
            txn.setNewNode(newNode);
            txn.setParentNodeId(ain.getNodeId());
            aaiWorkOnHand.incrementAndGet();
            supplyAsync(new PerformSelfLinkDeterminationTask(txn, null, aaiAdapter),
                aaiExecutorService).whenComplete((nodeTxn, error) -> {
                  
                  if (error != null) {
                    LOG.error(AaiUiMsgs.SELF_LINK_DETERMINATION_FAILED_GENERIC, selfLinkQuery);
                  } else {

                    OperationResult opResult = nodeTxn.getOpResult();

                    ActiveInventoryNode newChildNode = txn.getNewNode();

                    if (opResult != null && opResult.wasSuccessful()) {

                      if (!opResult.wasSuccessful()) {
                        numFailedLinkResolve.incrementAndGet();
                      }

                      if (opResult.isFromCache()) {
                        numSuccessfulLinkResolveFromCache.incrementAndGet();
                      } else {
                        numSuccessfulLinkResolveFromFromServer.incrementAndGet();
                      }

                      /*
                       * extract the self-link from the operational result.
                       */

                      Collection<JsonNode> entityLinks = new ArrayList<JsonNode>();
                      JsonNode genericQueryResult = null;
                      try {
                        genericQueryResult =
                            NodeUtils.convertJsonStrToJsonNode(nodeTxn.getOpResult().getResult());
                      } catch (Exception exc) {
                        LOG.error(AaiUiMsgs.JSON_CONVERSION_ERROR, JsonNode.class.toString(), exc.getMessage());
                      }

                      NodeUtils.extractObjectsByKey(genericQueryResult, "resource-link",
                          entityLinks);

                      String selfLink = null;

                      if (entityLinks.size() != 1) {

                        LOG.error(AaiUiMsgs.SELF_LINK_DETERMINATION_FAILED_UNEXPECTED_LINKS, String.valueOf(entityLinks.size()));
                          
                      } else {
                        selfLink = ((JsonNode) entityLinks.toArray()[0]).asText();
                        selfLink = ActiveInventoryAdapter.extractResourcePath(selfLink);

                        newChildNode.setSelfLink(selfLink);
                        newChildNode.setNodeId(NodeUtils.generateUniqueShaDigest(selfLink));

                        String uri = NodeUtils.calculateEditAttributeUri(selfLink);
                        if (uri != null) {
                          newChildNode.addProperty(SparkyConstants.URI_ATTR_NAME, uri);
                        }
                        
                        ActiveInventoryNode parent = nodeCache.get(txn.getParentNodeId());

                        if (parent != null) {
                          parent.addOutboundNeighbor(newChildNode.getNodeId());
                          newChildNode.addInboundNeighbor(parent.getNodeId());
                        }

                        newChildNode.setSelfLinkPendingResolve(false);
                        newChildNode.setSelfLinkProcessed(true);
                        newChildNode.changeState(NodeProcessingState.NEIGHBORS_UNPROCESSED,
                              NodeProcessingAction.SELF_LINK_RESPONSE_PARSE_OK);
                        
                        nodeCache.putIfAbsent(newChildNode.getNodeId(), newChildNode);
                        
                      }

                    } else {
                      LOG.error(AaiUiMsgs.SELF_LINK_RETRIEVAL_FAILED, txn.getQueryString(),
                          String.valueOf(nodeTxn.getOpResult().getResultCode()), nodeTxn.getOpResult().getResult());
                      newChildNode.setSelflinkRetrievalFailure(true);
                      newChildNode.setSelfLinkProcessed(true);
                      newChildNode.setSelfLinkPendingResolve(false);

                      newChildNode.changeState(NodeProcessingState.ERROR,
                          NodeProcessingAction.SELF_LINK_DETERMINATION_ERROR);

                    }

                  }
                  
                  aaiWorkOnHand.decrementAndGet();

                });

          }

          return true;

        } else {
          LOG.error(AaiUiMsgs.UNHANDLED_OBJ_TYPE_FOR_ENTITY_TYPE, entityType);
        }

      }
    } catch (Exception exc) {
      LOG.error(AaiUiMsgs.SELF_LINK_PROCESSING_ERROR, "Exception caught while"
          + " decoding complex attribute group - " + exc.getMessage());
    }

    return false;

  }

  /**
   * Process self link response.
   *
   * @param nodeId the node id
   */
  private void processSelfLinkResponse(String nodeId) {

    if (nodeId == null) {
      LOG.error(AaiUiMsgs.SELF_LINK_PROCESSING_ERROR, "Cannot process self link"
          + " response because nodeId is null");
      return;
    }

    ActiveInventoryNode ain = nodeCache.get(nodeId);

    if (ain == null) {
      LOG.error(AaiUiMsgs.SELF_LINK_PROCESSING_ERROR, "Cannot process self link response"
          + " because can't find node for id = " + nodeId);
      return;
    }

    JsonNode jsonNode = null;

    try {
      jsonNode = mapper.readValue(ain.getOpResult().getResult(), JsonNode.class);
    } catch (Exception exc) {
      LOG.error(AaiUiMsgs.SELF_LINK_JSON_PARSE_ERROR, "Failed to marshal json"
          + " response str into JsonNode with error, " + exc.getLocalizedMessage());
      ain.changeState(NodeProcessingState.ERROR,
          NodeProcessingAction.SELF_LINK_RESPONSE_PARSE_ERROR);
      return;
    }

    if (jsonNode == null) {
      LOG.error(AaiUiMsgs.SELF_LINK_JSON_PARSE_ERROR, "Failed to parse json node str."
          + " Parse resulted a null value.");
      ain.changeState(NodeProcessingState.ERROR,
          NodeProcessingAction.SELF_LINK_RESPONSE_PARSE_ERROR);
      return;
    }

    Iterator<Entry<String, JsonNode>> fieldNames = jsonNode.fields();
    Entry<String, JsonNode> field = null;

    RelationshipList relationshipList = null;

    while (fieldNames.hasNext()) {

      field = fieldNames.next();
      String fieldName = field.getKey();

      if ("relationship-list".equals(fieldName)) {

        try {
          relationshipList = mapper.readValue(field.getValue().toString(), RelationshipList.class);

          if (relationshipList != null) {
            ain.addRelationshipList(relationshipList);
          }

        } catch (Exception exc) {
          LOG.error(AaiUiMsgs.SELF_LINK_JSON_PARSE_ERROR, "Failed to parse relationship-list"
              + " attribute. Parse resulted in error, " + exc.getLocalizedMessage());
          ain.changeState(NodeProcessingState.ERROR,
              NodeProcessingAction.SELF_LINK_RESPONSE_PARSE_ERROR);
          return;
        }

      } else {

        JsonNode nodeValue = field.getValue();

        if (nodeValue != null && nodeValue.isValueNode()) {

          if (oxmEntityLookup.getEntityDescriptors().get(fieldName) == null) {

            /*
             * entity property name is not an entity, thus we can add this property name and value
             * to our property set
             */

            ain.addProperty(fieldName, nodeValue.asText());

          }

        } else {

          if (nodeValue.isArray()) {

            if (oxmEntityLookup.getEntityDescriptors().get(fieldName) == null) {

              /*
               * entity property name is not an entity, thus we can add this property name and value
               * to our property set
               */

              ain.addProperty(field.getKey(), nodeValue.toString());

            }

          } else {

            ain.addComplexGroup(nodeValue);

          }

        }
      }

    }

    String uri = NodeUtils.calculateEditAttributeUri(ain.getSelfLink());
    if (uri != null) {
      ain.addProperty(SparkyConstants.URI_ATTR_NAME, uri);
    }

    /*
     * We need a special behavior for intermediate entities from the REST model
     * 
     * Tenants are not top level entities, and when we want to visualization
     * their children, we need to construct keys that include the parent entity query
     * keys, the current entity type keys, and the child keys.   We'll always have the
     * current entity and children, but never the parent entity in the current (1707) REST
     * data model.
     * 
     * We have two possible solutions:
     * 
     * 1) Try to use the custom-query approach to learn about the entity keys
     *    - this could be done, but it could be very expensive for large objects.  When we do the first
     *      query to get a tenant, it will list all the in and out edges related to this entity,
     *      there is presently no way to filter this.  But the approach could be made to work and it would be
     *      somewhat data-model driven, other than the fact that we have to first realize that the entity
     *      that is being searched for is not top-level entity.  Once we have globally unique ids for resources
     *      this logic will not be needed and everything will be simpler.   The only reason we are in this logic
     *      at all is to be able to calculate a url for the child entities so we can hash it to generate 
     *      a globally unique id that can be safely used for the node.
     *      
     * *2* Extract the keys from the pathed self-link.
     *     This is a bad solution and I don't like it but it will be fast for all resource types, as the 
     *     information is already encoded in the URI.   When we get to a point where we switch to a better
     *     globally unique entity identity model, then a lot of the code being used to calculate an entity url
     *     to in-turn generate a deterministic globally unique id will disappear.      
     *     
     * 
     * right now we have the following:
     * 
     * - cloud-regions/cloud-region/{cloud-region-id}/{cloud-owner-id}/tenants/tenant/{tenant-id}
     *  
     */

    /*
     * For all entity types use the self-link extraction method to be consistent.  Once we have a
     * globally unique identity mechanism for entities, this logic can be revisited.
     */
    ain.clearQueryParams();
    ain.addQueryParams(extractQueryParamsFromSelfLink(ain.getSelfLink()));
      ain.changeState(NodeProcessingState.NEIGHBORS_UNPROCESSED,
          NodeProcessingAction.SELF_LINK_RESPONSE_PARSE_OK);
    

  }

  /**
   * Perform self link resolve.
   *
   * @param nodeId the node id
   */
  private void performSelfLinkResolve(String nodeId) {

    if (nodeId == null) {
      LOG.error(AaiUiMsgs.SELF_LINK_PROCESSING_ERROR, "Resolve of self-link"
          + " has been skipped because provided nodeId is null");
      return;
    }

    ActiveInventoryNode ain = nodeCache.get(nodeId);

    if (ain == null) {
      LOG.error(AaiUiMsgs.SELF_LINK_PROCESSING_ERROR, "Failed to find node with id, " + nodeId
          + ", from node cache. Resolve self-link method has been skipped.");
      return;
    }

    if (!ain.isSelfLinkPendingResolve()) {

      ain.setSelfLinkPendingResolve(true);

      // kick off async self-link resolution

      if (LOG.isDebugEnabled()) {
        LOG.debug(AaiUiMsgs.DEBUG_GENERIC, 
            "About to process node in SELF_LINK_UNPROCESSED State, link = " + ain.getSelfLink());
      }

      numLinksDiscovered.incrementAndGet();

      String depthModifier = DEPTH_ALL_MODIFIER;

      /*
       * If the current node is the search target, we want to see everything the node has to offer
       * from the self-link and not filter it to a single node.
       */

      if (visualizationConfigs.getShallowEntities().contains(ain.getEntityType())
          && !ain.isRootNode()) {
        depthModifier = NODES_ONLY_MODIFIER;
      }

      NodeProcessingTransaction txn = new NodeProcessingTransaction();
      txn.setProcessingNode(ain);
      txn.setRequestParameters(depthModifier);
      aaiWorkOnHand.incrementAndGet();
      supplyAsync(
          new PerformNodeSelfLinkProcessingTask(txn, depthModifier, aaiAdapter),
          aaiExecutorService).whenComplete((nodeTxn, error) -> {
            
            if (error != null) {

              /*
               * an error processing the self link should probably result in the node processing
               * state shifting to ERROR
               */

              nodeTxn.getProcessingNode().setSelflinkRetrievalFailure(true);

              nodeTxn.getProcessingNode().changeState(NodeProcessingState.ERROR,
                  NodeProcessingAction.SELF_LINK_RESOLVE_ERROR);

              nodeTxn.getProcessingNode().setSelfLinkPendingResolve(false);

            } else {

              totalLinksRetrieved.incrementAndGet();

              OperationResult opResult = nodeTxn.getOpResult();

              if (opResult != null && opResult.wasSuccessful()) {

                if (!opResult.wasSuccessful()) {
                  numFailedLinkResolve.incrementAndGet();
                }

                if (opResult.isFromCache()) {
                  numSuccessfulLinkResolveFromCache.incrementAndGet();
                } else {
                  numSuccessfulLinkResolveFromFromServer.incrementAndGet();
                }

                // success path
                nodeTxn.getProcessingNode().setOpResult(opResult);
                nodeTxn.getProcessingNode().changeState(
                    NodeProcessingState.SELF_LINK_RESPONSE_UNPROCESSED,
                    NodeProcessingAction.SELF_LINK_RESOLVE_OK);

                nodeTxn.getProcessingNode().setSelfLinkProcessed(true);
                nodeTxn.getProcessingNode().setSelfLinkPendingResolve(false);

              } else {
                LOG.error(AaiUiMsgs.SELF_LINK_PROCESSING_ERROR, "Self Link retrieval for link,"
                    + txn.getSelfLinkWithModifiers() + ", failed with error code,"
                    + nodeTxn.getOpResult().getResultCode() + ", and message,"
                    + nodeTxn.getOpResult().getResult());

                nodeTxn.getProcessingNode().setSelflinkRetrievalFailure(true);
                nodeTxn.getProcessingNode().setSelfLinkProcessed(true);

                nodeTxn.getProcessingNode().changeState(NodeProcessingState.ERROR,
                    NodeProcessingAction.SELF_LINK_RESOLVE_ERROR);

                nodeTxn.getProcessingNode().setSelfLinkPendingResolve(false);

              }
            }
            
            aaiWorkOnHand.decrementAndGet();

          });

    }

  }


  /**
   * Process neighbors.
   *
   * @param nodeId the node id
   */
  private void processNeighbors(String nodeId) {
    
    if (nodeId == null) {
      LOG.error(AaiUiMsgs.SELF_LINK_PROCESS_NEIGHBORS_ERROR, "Failed to process"
          + " neighbors because nodeId is null.");
      return;
    }

    ActiveInventoryNode ain = nodeCache.get(nodeId);

    if (ain == null) {
      LOG.error(AaiUiMsgs.SELF_LINK_PROCESS_NEIGHBORS_ERROR, "Failed to process"
          + " neighbors because node could not be found in nodeCache with id, " + nodeId);
      return;
    }

    /*
     * process complex attribute and relationships
     */

    boolean neighborsProcessedSuccessfully = true;

    for (JsonNode n : ain.getComplexGroups()) {
      neighborsProcessedSuccessfully &= decodeComplexAttributeGroup(ain, n);
    }

    for (RelationshipList relationshipList : ain.getRelationshipLists()) {
      neighborsProcessedSuccessfully &= addSelfLinkRelationshipChildren(ain, relationshipList);
    }


    if (neighborsProcessedSuccessfully) {
      ain.changeState(NodeProcessingState.READY, NodeProcessingAction.NEIGHBORS_PROCESSED_OK);
    } else {
      ain.changeState(NodeProcessingState.ERROR, NodeProcessingAction.NEIGHBORS_PROCESSED_ERROR);
    }
  

    /*
     * If neighbors fail to process, there is already a call to change the state within the
     * relationship and neighbor processing functions.
     */

  }

  /**
   * Find and mark root node.
   *
   * @param queryParams the query params
   * @return true, if successful
   */
  private void findAndMarkRootNode(QueryParams queryParams) {

    if (isRootNodeFound()) {
      return;
    }

    for (ActiveInventoryNode cacheNode : nodeCache.values()) {

      if (queryParams.getSearchTargetNodeId().equals(cacheNode.getNodeId())) {
        cacheNode.setNodeDepth(0);
        cacheNode.setRootNode(true);
        LOG.info(AaiUiMsgs.ROOT_NODE_DISCOVERED, queryParams.getSearchTargetNodeId());
        setRootNodeFound(true);
      }
    }

  }

  /**
   * Process current node states.
   *
   * @param rootNodeDiscovered the root node discovered
   */
  private void processCurrentNodeStates(QueryParams queryParams) {
    /*
     * Force an evaluation of node depths before determining if we should limit state-based
     * traversal or processing.
     */
    
    findAndMarkRootNode(queryParams);
    
    verifyOutboundNeighbors();

    for (ActiveInventoryNode cacheNode : nodeCache.values()) {

      if (LOG.isDebugEnabled()) {
        LOG.debug(AaiUiMsgs.DEBUG_GENERIC, 
            "processCurrentNodeState(), nid = "
            + cacheNode.getNodeId() + " , nodeDepth = " + cacheNode.getNodeDepth());
      }

      switch (cacheNode.getState()) {

        case INIT: {
          processInitialState(cacheNode.getNodeId());
          break;
        }

        case READY:
        case ERROR: {
          break;
        }

        case SELF_LINK_UNRESOLVED: {
          performSelfLinkResolve(cacheNode.getNodeId());
          break;
        }

        case SELF_LINK_RESPONSE_UNPROCESSED: {
          processSelfLinkResponse(cacheNode.getNodeId());
          break;
        }

        case NEIGHBORS_UNPROCESSED: {

          /*
           * We use the rootNodeDiscovered flag to ignore depth retrieval thresholds until the root
           * node is identified. Then the evaluative depth calculations should re-balance the graph
           * around the root node.
           */
          
          if (!isRootNodeFound() || cacheNode.getNodeDepth() < this.visualizationConfigs
              .getMaxSelfLinkTraversalDepth()) {

            if (LOG.isDebugEnabled()) {
              LOG.debug(AaiUiMsgs.DEBUG_GENERIC, 
                  "processCurrentNodeState() -- Node at max depth,"
                  + " halting processing at current state = -- "
                      + cacheNode.getState() + " nodeId = " + cacheNode.getNodeId());
            }
            
            processNeighbors(cacheNode.getNodeId());

          }

          break;
        }
        default:
          break;
      }

    }

  }

  /**
   * Adds the complex group to node.
   *
   * @param targetNode the target node
   * @param attributeGroup the attribute group
   * @return true, if successful
   */
  private boolean addComplexGroupToNode(ActiveInventoryNode targetNode, JsonNode attributeGroup) {

    if (attributeGroup == null) {
      targetNode.changeState(NodeProcessingState.ERROR,
          NodeProcessingAction.COMPLEX_ATTRIBUTE_GROUP_PARSE_OK);
      return false;
    }

    RelationshipList relationshipList = null;

    if (attributeGroup.isObject()) {

      Iterator<Entry<String, JsonNode>> fields = attributeGroup.fields();
      Entry<String, JsonNode> field = null;
      String fieldName;
      JsonNode fieldValue;

      while (fields.hasNext()) {
        field = fields.next();
        fieldName = field.getKey();
        fieldValue = field.getValue();

        if (fieldValue.isObject()) {

          if (fieldName.equals("relationship-list")) {

            try {
              relationshipList =
                  mapper.readValue(field.getValue().toString(), RelationshipList.class);

              if (relationshipList != null) {
                targetNode.addRelationshipList(relationshipList);
              }

            } catch (Exception exc) {
              LOG.error(AaiUiMsgs.SELF_LINK_JSON_PARSE_ERROR, "Failed to parse"
                  + " relationship-list attribute. Parse resulted in error, "
                  + exc.getLocalizedMessage());
              targetNode.changeState(NodeProcessingState.ERROR,
                  NodeProcessingAction.COMPLEX_ATTRIBUTE_GROUP_PARSE_ERROR);
              return false;
            }

          } else {
            targetNode.addComplexGroup(fieldValue);
          }

        } else if (fieldValue.isArray()) {
          if (LOG.isDebugEnabled()) {
            LOG.debug(AaiUiMsgs.DEBUG_GENERIC, 
                "Unexpected array type with a key = " + fieldName);
          }
        } else if (fieldValue.isValueNode()) {
          if (oxmEntityLookup.getEntityDescriptors().get(field.getKey()) == null) {
            /*
             * property key is not an entity type, add it to our property set.
             */
            targetNode.addProperty(field.getKey(), fieldValue.asText());
          }

        }
      }

    } else if (attributeGroup.isArray()) {
      if (LOG.isDebugEnabled()) {
        LOG.debug(AaiUiMsgs.DEBUG_GENERIC, 
            "Unexpected array type for attributeGroup = " + attributeGroup);
      }
    } else if (attributeGroup.isValueNode()) {
      if (LOG.isDebugEnabled()) {
        LOG.debug(AaiUiMsgs.DEBUG_GENERIC, 
            "Unexpected value type for attributeGroup = " + attributeGroup);
      }
    }
    
    return true;
  }
  
  public int getNumSuccessfulLinkResolveFromCache() {
    return numSuccessfulLinkResolveFromCache.get();
  }

  public int getNumSuccessfulLinkResolveFromFromServer() {
    return numSuccessfulLinkResolveFromFromServer.get();
  }

  public int getNumFailedLinkResolve() {
    return numFailedLinkResolve.get();
  }

  public InlineMessage getInlineMessage() {
    return inlineMessage;
  }

  public void setInlineMessage(InlineMessage inlineMessage) {
    this.inlineMessage = inlineMessage;
  }

  public void setMaxSelfLinkTraversalDepth(int depth) {
    this.maxSelfLinkTraversalDepth = depth;
  }

  public int getMaxSelfLinkTraversalDepth() {
    return this.maxSelfLinkTraversalDepth;
  }

  public ConcurrentHashMap<String, ActiveInventoryNode> getNodeCache() {
    return nodeCache;
  }

  /**
   * Gets the relationship primary key values.
   *
   * @param r the r
   * @param entityType the entity type
   * @param pkeyNames the pkey names
   * @return the relationship primary key values
   */
  private String getRelationshipPrimaryKeyValues(Relationship r, String entityType,
      List<String> pkeyNames) {

    StringBuilder sb = new StringBuilder(64);

    if (pkeyNames.size() > 0) {
      String primaryKey = extractKeyValueFromRelationData(r, entityType + "." + pkeyNames.get(0));
      if (primaryKey != null) {

        sb.append(primaryKey);

      } else {
        // this should be a fatal error because unless we can
        // successfully retrieve all the expected keys we'll end up
        // with a garbage node
        LOG.error(AaiUiMsgs.EXTRACTION_ERROR, "ERROR: Failed to extract"
            + " keyName, " + entityType + "." + pkeyNames.get(0)
            + ", from relationship data, " + r.toString());
        return null;
      }

      for (int i = 1; i < pkeyNames.size(); i++) {

        String kv = extractKeyValueFromRelationData(r, entityType + "." + pkeyNames.get(i));
        if (kv != null) {
          sb.append("/").append(kv);
        } else {
          // this should be a fatal error because unless we can
          // successfully retrieve all the expected keys we'll end up
          // with a garbage node
          LOG.error(AaiUiMsgs.EXTRACTION_ERROR, "ERROR:  failed to extract keyName, "
              + entityType + "." + pkeyNames.get(i)
              + ", from relationship data, " + r.toString());
          return null;
        }
      }

      return sb.toString();

    }

    return null;

  }

  /**
   * Extract key value from relation data.
   *
   * @param r the r
   * @param keyName the key name
   * @return the string
   */
  private String extractKeyValueFromRelationData(Relationship r, String keyName) {

    RelationshipData[] rdList = r.getRelationshipData();

    for (RelationshipData relData : rdList) {

      if (relData.getRelationshipKey().equals(keyName)) {
        return relData.getRelationshipValue();
      }
    }

    return null;
  }

  /**
   * Determine node id and key.
   *
   * @param ain the ain
   * @return true, if successful
   */
  private boolean addNodeQueryParams(ActiveInventoryNode ain) {

    if (ain == null) {
      LOG.error(AaiUiMsgs.FAILED_TO_DETERMINE_NODE_ID, "ActiveInventoryNode is null");
      return false;
    }

    List<String> pkeyNames =
        oxmEntityLookup.getEntityDescriptors().get(ain.getEntityType()).getPrimaryKeyAttributeNames();

    if (pkeyNames == null || pkeyNames.size() == 0) {
      LOG.error(AaiUiMsgs.FAILED_TO_DETERMINE_NODE_ID, "Primary key names is empty");
      return false;
    }

    StringBuilder sb = new StringBuilder(64);

    if (pkeyNames.size() > 0) {
      String primaryKey = ain.getProperties().get(pkeyNames.get(0));
      if (primaryKey != null) {
        sb.append(primaryKey);
      } else {
        // this should be a fatal error because unless we can
        // successfully retrieve all the expected keys we'll end up
        // with a garbage node
        LOG.error(AaiUiMsgs.EXTRACTION_ERROR, "ERROR: Failed to extract keyName, "
            + pkeyNames.get(0) + ", from entity properties");
        return false;
      }

      for (int i = 1; i < pkeyNames.size(); i++) {

        String kv = ain.getProperties().get(pkeyNames.get(i));
        if (kv != null) {
          sb.append("/").append(kv);
        } else {
          // this should be a fatal error because unless we can
          // successfully retrieve all the expected keys we'll end up
          // with a garbage node
          LOG.error(AaiUiMsgs.EXTRACTION_ERROR, "ERROR: Failed to extract keyName, "
              + pkeyNames.get(i) + ", from entity properties");
          return false;
        }
      }

      /*final String nodeId = NodeUtils.generateUniqueShaDigest(ain.getEntityType(),
          NodeUtils.concatArray(pkeyNames, "/"), sb.toString());*/

      //ain.setNodeId(nodeId);
      ain.setPrimaryKeyName(NodeUtils.concatArray(pkeyNames, "/"));
      ain.setPrimaryKeyValue(sb.toString());
      
      if (ain.getEntityType() != null && ain.getPrimaryKeyName() != null
          && ain.getPrimaryKeyValue() != null) {
        ain.addQueryParam(
            ain.getEntityType() + "." + ain.getPrimaryKeyName() + ":" + ain.getPrimaryKeyValue());
      }
      return true;

    }

    return false;

  }

  /**
   * Adds the self link relationship children.
   *
   * @param processingNode the processing node
   * @param relationshipList the relationship list
   * @return true, if successful
   */
  private boolean addSelfLinkRelationshipChildren(ActiveInventoryNode processingNode,
      RelationshipList relationshipList) {

    if (relationshipList == null) {
      LOG.debug(AaiUiMsgs.DEBUG_GENERIC, "No relationships added to parent node = "
          + processingNode.getNodeId() + " because relationshipList is empty");
      processingNode.changeState(NodeProcessingState.ERROR,
          NodeProcessingAction.NEIGHBORS_PROCESSED_ERROR);
      return false;
    }

    Relationship[] relationshipArray = relationshipList.getRelationshipList();
    OxmEntityDescriptor descriptor = null;
    String repairedSelfLink = null;

    if (relationshipArray != null) {

      ActiveInventoryNode newNode = null;
      String resourcePath = null;

      for (Relationship r : relationshipArray) {
        
        resourcePath = ActiveInventoryAdapter.extractResourcePath(r.getRelatedLink());

        String nodeId = NodeUtils.generateUniqueShaDigest(resourcePath);

        if (nodeId == null) {

          LOG.error(AaiUiMsgs.SKIPPING_RELATIONSHIP, r.toString());
          processingNode.changeState(NodeProcessingState.ERROR,
              NodeProcessingAction.NODE_IDENTITY_ERROR);
          return false;
        }

        newNode = new ActiveInventoryNode(this.visualizationConfigs, oxmEntityLookup);

        String entityType = r.getRelatedTo();

        if (r.getRelationshipData() != null) {
          for (RelationshipData rd : r.getRelationshipData()) {
            newNode.addQueryParam(rd.getRelationshipKey() + ":" + rd.getRelationshipValue());
          }
        }

        descriptor = oxmEntityLookup.getEntityDescriptors().get(r.getRelatedTo());

        newNode.setNodeId(nodeId);
        newNode.setEntityType(entityType);
        newNode.setSelfLink(resourcePath);

        processingNode.addOutboundNeighbor(nodeId);

        if (descriptor != null) {

          List<String> pkeyNames = descriptor.getPrimaryKeyAttributeNames();

          newNode.changeState(NodeProcessingState.SELF_LINK_UNRESOLVED,
              NodeProcessingAction.SELF_LINK_SET);

          newNode.setPrimaryKeyName(NodeUtils.concatArray(pkeyNames, "/"));

          String primaryKeyValues = getRelationshipPrimaryKeyValues(r, entityType, pkeyNames);
          newNode.setPrimaryKeyValue(primaryKeyValues);

        } else {

          LOG.error(AaiUiMsgs.VISUALIZATION_OUTPUT_ERROR,
              "Failed to parse entity because OXM descriptor could not be found for type = "
                  + r.getRelatedTo());

          newNode.changeState(NodeProcessingState.ERROR,
              NodeProcessingAction.NEIGHBORS_PROCESSED_ERROR);

        }

        if (nodeCache.putIfAbsent(nodeId, newNode) != null) {
          if (LOG.isDebugEnabled()) {
            LOG.debug(AaiUiMsgs.DEBUG_GENERIC,
                "Failed to add node to nodeCache because it already exists.  Node id = "
                    + newNode.getNodeId());
          }
        }

      }

    }

    return true;

  }

  /**
   * Process initial state.
   *
   * @param nodeId the node id
   */
  private void processInitialState(String nodeId) {

    if (nodeId == null) {
      LOG.error(AaiUiMsgs.FAILED_TO_PROCESS_INITIAL_STATE, "Node id is null");
      return;
    }

    ActiveInventoryNode cachedNode = nodeCache.get(nodeId);

    if (cachedNode == null) {
      LOG.error(AaiUiMsgs.FAILED_TO_PROCESS_INITIAL_STATE, "Node cannot be"
          + " found for nodeId, " + nodeId);
      return;
    }

    if (cachedNode.getSelfLink() == null) {

      if (cachedNode.getNodeId() == null ) {

        /*
         * if the self link is null at the INIT state, which could be valid if this node is a
         * complex attribute group which didn't originate from a self-link, but in that situation
         * both the node id and node key should already be set.
         */

        cachedNode.changeState(NodeProcessingState.ERROR, NodeProcessingAction.NODE_IDENTITY_ERROR);

      }

      if (cachedNode.getNodeId() != null) {

        /*
         * This should be the success path branch if the self-link is not set
         */

        cachedNode.changeState(NodeProcessingState.SELF_LINK_RESPONSE_UNPROCESSED,
            NodeProcessingAction.SELF_LINK_RESPONSE_PARSE_OK);

      }

    } else {

      if (cachedNode.hasResolvedSelfLink()) {
        LOG.error(AaiUiMsgs.INVALID_RESOLVE_STATE_DURING_INIT);
        cachedNode.changeState(NodeProcessingState.ERROR,
            NodeProcessingAction.UNEXPECTED_STATE_TRANSITION);
      } else {
        cachedNode.changeState(NodeProcessingState.SELF_LINK_UNRESOLVED,
            NodeProcessingAction.SELF_LINK_SET);
      }
    }
  }

  /**
   * Process skeleton node.
   *
   * @param skeletonNode the skeleton node
   * @param queryParams the query params
   */
  private void processSearchableEntity(SearchableEntity searchTargetEntity, QueryParams queryParams) {

    if (searchTargetEntity == null) {
      return;
    }

    if (searchTargetEntity.getId() == null) {
      LOG.error(AaiUiMsgs.FAILED_TO_PROCESS_SKELETON_NODE, "Failed to process skeleton"
          + " node because nodeId is null for node, " + searchTargetEntity.getLink());
      return;
    }

    ActiveInventoryNode newNode = new ActiveInventoryNode(this.visualizationConfigs, oxmEntityLookup);

    newNode.setNodeId(searchTargetEntity.getId());
    newNode.setEntityType(searchTargetEntity.getEntityType());
    newNode.setPrimaryKeyName(getEntityTypePrimaryKeyName(searchTargetEntity.getEntityType()));
    newNode.setPrimaryKeyValue(searchTargetEntity.getEntityPrimaryKeyValue());
    
    if (newNode.getEntityType() != null && newNode.getPrimaryKeyName() != null
        && newNode.getPrimaryKeyValue() != null) {
      newNode.addQueryParam(
          newNode.getEntityType() + "." + newNode.getPrimaryKeyName() + ":" + newNode.getPrimaryKeyValue());
    }
    /*
     * This code may need some explanation. In any graph there will be a single root node. The root
     * node is really the center of the universe, and for now, we are tagging the search target as
     * the root node. Everything else in the visualization of the graph will be centered around this
     * node as the focal point of interest.
     * 
     * Due to it's special nature, there will only ever be one root node, and it's node depth will
     * always be equal to zero.
     */

    if (!isRootNodeFound()) {
      if (queryParams.getSearchTargetNodeId().equals(newNode.getNodeId())) {
        newNode.setNodeDepth(0);
        newNode.setRootNode(true);
        LOG.info(AaiUiMsgs.ROOT_NODE_DISCOVERED, queryParams.getSearchTargetNodeId());
        setRootNodeFound(true);
      }
    }

    newNode.setSelfLink(searchTargetEntity.getLink());

    nodeCache.putIfAbsent(newNode.getNodeId(), newNode);
  }

  private int getTotalWorkOnHand() {
    
    int numNodesWithPendingStates = 0;
    
    if( isRootNodeFound()) {
      evaluateNodeDepths();
    }
    
    for (ActiveInventoryNode n : nodeCache.values()) {

      switch (n.getState()) {

        case READY:
        case ERROR: {
          // do nothing, these are our normal
          // exit states
          break;
        }

        case NEIGHBORS_UNPROCESSED: {

          if (n.getNodeDepth() < this.visualizationConfigs.getMaxSelfLinkTraversalDepth()) {
            /*
             * Only process our neighbors relationships if our current depth is less than the max
             * depth
             */
            numNodesWithPendingStates++;
          }

          break;
        }

        default: {

          /*
           * for all other states, there is work to be done
           */
          numNodesWithPendingStates++;
        }

      }

    }

    LOG.debug(AaiUiMsgs.OUTSTANDING_WORK_PENDING_NODES,
        String.valueOf(numNodesWithPendingStates));

    int totalWorkOnHand = aaiWorkOnHand.get() + numNodesWithPendingStates;
    
    return totalWorkOnHand;
    
  }
  
  /**
   * Checks for out standing work.
   *
   * @return true, if successful
   */
  private void processOutstandingWork(QueryParams queryParams) {
    
    while (getTotalWorkOnHand() > 0) {

      /*
       * Force an evaluation of node depths before determining if we should limit state-based
       * traversal or processing.
       */

      processCurrentNodeStates(queryParams);

      try {
        Thread.sleep(10);
      } catch (InterruptedException exc) {
        LOG.error(AaiUiMsgs.PROCESSING_LOOP_INTERUPTED, exc.getMessage());
        Thread.currentThread().interrupt();
        return;
      }

    }

  }

  /* (non-Javadoc)
   * @see org.onap.aai.sparky.viewandinspect.services.VisualizationContext#processSelfLinks(org.onap.aai.sparky.sync.entity.SearchableEntity, org.onap.aai.sparky.viewandinspect.entity.QueryParams)
   */
  @Override
  public void processSelfLinks(SearchableEntity searchtargetEntity, QueryParams queryParams) {

    try {


      if (searchtargetEntity == null) {
        LOG.error(AaiUiMsgs.SELF_LINK_PROCESSING_ERROR, contextIdStr + " - Failed to"
            + " processSelfLinks, searchtargetEntity is null");
        return;
      }

      long startTimeInMs = System.currentTimeMillis();

      processSearchableEntity(searchtargetEntity, queryParams);
      
      /*
       * This method is blocking until we decouple it with a CountDownLatch await condition,
       * and make the internal graph processing more event-y.
       */
      
      processOutstandingWork(queryParams);

      long totalResolveTime = (System.currentTimeMillis() - startTimeInMs);
      
      long opTime = System.currentTimeMillis() - startTimeInMs;

      LOG.info(AaiUiMsgs.ALL_TRANSACTIONS_RESOLVED, String.valueOf(totalResolveTime),
          String.valueOf(totalLinksRetrieved.get()), String.valueOf(opTime));

    } catch (Exception exc) {
      LOG.error(AaiUiMsgs.VISUALIZATION_OUTPUT_ERROR, exc.getMessage());
    }

  }

  /**
   * Verify outbound neighbors.
   */
  private void verifyOutboundNeighbors() {

    for (ActiveInventoryNode srcNode : nodeCache.values()) {

      for (String targetNodeId : srcNode.getOutboundNeighbors()) {

        ActiveInventoryNode targetNode = nodeCache.get(targetNodeId);

        if (targetNode != null && srcNode.getNodeId() != null) {

          targetNode.addInboundNeighbor(srcNode.getNodeId());

          if (this.visualizationConfigs.makeAllNeighborsBidirectional()) {
            targetNode.addOutboundNeighbor(srcNode.getNodeId());
          }

        }

      }

    }

  }

  /**
   * Evaluate node depths.
   */
  private void evaluateNodeDepths() {

    int numChanged = -1;
    int numAttempts = 0;

    while (numChanged != 0) {

      numChanged = 0;
      numAttempts++;

      for (ActiveInventoryNode srcNode : nodeCache.values()) {

        if (srcNode.getState() == NodeProcessingState.INIT) {

          /*
           * this maybe the only state that we don't want to to process the node depth on, because
           * typically it won't have any valid fields set, and it may remain in a partial state
           * until we have processed the self-link.
           */

          continue;

        }

        for (String targetNodeId : srcNode.getOutboundNeighbors()) {
          ActiveInventoryNode targetNode = nodeCache.get(targetNodeId);

          if (targetNode != null) {

            if (targetNode.changeDepth(srcNode.getNodeDepth() + 1)) {
              numChanged++;
            }
          }
        }

        for (String targetNodeId : srcNode.getInboundNeighbors()) {
          ActiveInventoryNode targetNode = nodeCache.get(targetNodeId);

          if (targetNode != null) {

            if (targetNode.changeDepth(srcNode.getNodeDepth() + 1)) {
              numChanged++;
            }
          }
        }
      }

      if (numAttempts >= MAX_DEPTH_EVALUATION_ATTEMPTS) {
        LOG.info(AaiUiMsgs.MAX_EVALUATION_ATTEMPTS_EXCEEDED);
        return;
      }

    }

    if (LOG.isDebugEnabled()) {
      if (numAttempts > 0) {
        LOG.debug(AaiUiMsgs.DEBUG_GENERIC, 
            "Evaluate node depths completed in " + numAttempts + " attempts");
      } else {
        LOG.debug(AaiUiMsgs.DEBUG_GENERIC, 
            "Evaluate node depths completed in 0 attempts because all nodes at correct depth");
      }
    }

  }


  /**
   * Gets the entity type primary key name.
   *
   * @param entityType the entity type
   * @return the entity type primary key name
   */

  
  private String getEntityTypePrimaryKeyName(String entityType) {

    if (entityType == null) {
      LOG.error(AaiUiMsgs.FAILED_TO_DETERMINE, "node primary key"
          + " name because entity type is null");
      return null;
    }

    OxmEntityDescriptor descriptor = oxmEntityLookup.getEntityDescriptors().get(entityType);

    if (descriptor == null) {
      LOG.error(AaiUiMsgs.FAILED_TO_DETERMINE, "oxm entity"
          + " descriptor for entityType = " + entityType);
      return null;
    }

    List<String> pkeyNames = descriptor.getPrimaryKeyAttributeNames();

    if (pkeyNames == null || pkeyNames.size() == 0) {
      LOG.error(AaiUiMsgs.FAILED_TO_DETERMINE, "node primary"
          + " key because descriptor primary key names is empty");
      return null;
    }

    return NodeUtils.concatArray(pkeyNames, "/");

  }

}