summaryrefslogtreecommitdiffstats
path: root/src/main/java/org/openecomp/sparky/viewandinspect/services/VisualizationContext.java
blob: 3bcd06e91f82932337baf7620c41a11bf3001b23 (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

@media only all and (prefers-color-scheme: dark) {
.highlight .hll { background-color: #49483e }
.highlight .c { color: #75715e } /* Comment */
.highlight .err { color: #960050; background-color: #1e0010 } /* Error */
.highlight .k { color: #66d9ef } /* Keyword */
.highlight .l { color: #ae81ff } /* Literal */
.highlight .n { color: #f8f8f2 } /* Name */
.highlight .o { color: #f92672 } /* Operator */
.highlight .p { color: #f8f8f2 } /* Punctuation */
.highlight .ch { color: #75715e } /* Comment.Hashbang */
.highlight .cm { color: #75715e } /* Comment.Multiline */
.highlight .cp { color: #75715e } /* Comment.Preproc */
.highlight .cpf { color: #75715e } /* Comment.PreprocFile */
.highlight .c1 { color: #75715e } /* Comment.Single */
.highlight .cs { color: #75715e } /* Comment.Special */
.highlight .gd { color: #f92672 } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .gi { color: #a6e22e } /* Generic.Inserted */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #75715e } /* Generic.Subheading */
.highlight .kc { color: #66d9ef } /* Keyword.Constant */
.highlight .kd { color: #66d9ef } /* Keyword.Declaration */
.highlight .kn { color: #f92672 } /* Keyword.Namespace */
.highlight .kp { color: #66d9ef } /* Keyword.Pseudo */
.highlight .kr { color: #66d9ef } /* Keyword.Reserved */
.highlight .kt { color: #66d9ef } /* Keyword.Type */
.highlight .ld { color: #e6db74 } /* Literal.Date */
.highlight .m { color: #ae81ff } /* Literal.Number */
.highlight .s { color: #e6db74 } /* Literal.String */
.highlight .na { color: #a6e22e } /* Name.Attribute */
.highlight .nb { color: #f8f8f2 } /* Name.Builtin */
.highlight .nc { color: #a6e22e } /* Name.Class */
.highlight .no { color: #66d9ef } /* Name.Constant */
.highlight .nd { color: #a6e22e } /* Name.Decorator */
.highlight .ni { color: #f8f8f2 } /* Name.Entity */
.highlight .ne { color: #a6e22e } /* Name.Exception */
.highlight .nf { color: #a6e22e } /* Name.Function */
.highlight .nl { color: #f8f8f2 } /* Name.Label */
.highlight .nn { color: #f8f8f2 } /* Name.Namespace */
.highlight .nx { color: #a6e22e } /* Name.Other */
.highlight .py { color: #f8f8f2 } /* Name.Property */
.highlight .nt { color: #f92672 } /* Name.Tag */
.highlight .nv { color: #f8f8f2 } /* Name.Variable */
.highlight .ow { color: #f92672 } /* Operator.Word */
.highlight .w { color: #f8f8f2 } /* Text.Whitespace */
.highlight .mb { color: #ae81ff } /* Literal.Number.Bin */
.highlight .mf { color: #ae81ff } /* Literal.Number.Float */
.highlight .mh { color: #ae81ff } /* Literal.Number.Hex */
.highlight .mi { color: #ae81ff } /* Literal.Number.Integer */
.highlight .mo { color: #ae81ff } /* Literal.Number.Oct */
.highlight .sa { color: #e6db74 } /* Literal.String.Affix */
.highlight .sb { color: #e6db74 } /* Literal.String.Backtick */
.highlight .sc { color: #e6db74 } /* Literal.String.Char */
.highlight .dl { color: #e6db74 } /* Literal.String.Delimiter */
.highlight .sd { color: #e6db74 } /* Literal.String.Doc */
.highlight .s2 { color: #e6db74 } /* Literal.String.Double */
.highlight .se { color: #ae81ff } /* Literal.String.Escape */
.highlight .sh { color: #e6db74 } /* Literal.String.Heredoc */
.highlight .si { color: #e6db74 } /* Literal.String.Interpol */
.highlight .sx { color: #e6db74 } /* Literal.String.Other */
.highlight .sr { color: #e6db74 } /* Literal.String.Regex */
.highlight .s1 { color: #e6db74 } /* Literal.String.Single */
.highlight .ss { color: #e6db74 } /* Literal.String.Symbol */
.highlight .bp { color: #f8f8f2 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #a6e22e } /* Name.Function.Magic */
.highlight .vc { color: #f8f8f2 } /* Name.Variable.Class */
.highlight .vg { color: #f8f8f2 } /* Name.Variable.Global */
.highlight .vi { color: #f8f8f2 } /* Name.Variable.Instance */
.highlight .vm { color: #f8f8f2 } /* Name.Variable.Magic */
.highlight .il { color: #ae81ff } /* Literal.Number.Integer.Long */
}
@media (prefers-color-scheme: light) {
.highlight .hll { background-color: #ffffcc }
.highlight .c { color: #888888 } /* Comment */
.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */
.highlight .k { color: #008800; font-weight: bold } /* Keyword */
.highlight .ch { color: #888888 } /* Comment.Hashbang */
.highlight .cm { color: #888888 } /* Comment.Multiline */
.highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */
.highlight .cpf { color: #888888 } /* Comment.PreprocFile */
.highlight .c1 { color: #888888 } /* Comment.Single */
.highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */
.highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .gr { color: #aa0000 } /* Generic.Error */
.highlight .gh { color: #333333 } /* Generic.Heading */
.highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */
.highlight .go { color: #888888 } /* Generic.Output */
.highlight .gp { color: #555555 } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #666666 } /* Generic.Subheading */
.highlight .gt { color: #aa0000 } /* Generic.Traceback */
.highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #008800 } /* Keyword.Pseudo */
.highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */
.highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */
.highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */
.highlight .na { color: #336699 } /* Name.Attribute */
.highlight .nb { color: #003388 } /* Name.Builtin */
.highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */
.highlight .no { color: #003366; font-weight: bold } /* Name.Constant */
.highlight .nd { color: #555555 } /* Name.Decorator */
.highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */
.highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */
.highlight .nl { color: #336699; font-style: italic } /* Name.Label */
.highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */
.highlight .py { color: #336699; font-weight: bold } /* Name.Property */
.highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */
.highlight .nv { color: #336699 } /* Name.Variable */
.highlight .ow { color: #008800 } /* Operator.Word */
.highlight .w { color: #bbbbbb } /* Text.Whitespace */
.highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */
.highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */
.highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */
.highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */
.highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */
.highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */
.highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */
.highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */
.highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */
.highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */
.highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */
.highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */
.highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */
.highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */
.highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */
.highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */
.highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */
.highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */
.highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */
.highlight .vc { color: #336699 } /* Name.Variable.Class */
.highlight .vg { color: #dd7700 } /* Name.Variable.Global */
.highlight .vi { color: #3333bb } /* Name.Variable.Instance */
.highlight .vm { color: #336699 } /* Name.Variable.Magic */
.highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
}
/**
 * ============LICENSE_START===================================================
 * SPARKY (AAI UI service)
 * ============================================================================
 * Copyright © 2017 AT&T Intellectual Property.
 * Copyright © 2017 Amdocs
 * All rights reserved.
 * ============================================================================
 * 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=====================================================
 *
 * ECOMP and OpenECOMP are trademarks
 * and service marks of AT&T Intellectual Property.
 */

package org.openecomp.sparky.viewandinspect.entity;

/*
 * Expected JSON Output:
 * 
 * { JsonNodeLink : { id : <value>, source : <value>, target : <value> } }
 * 
 */

/**
 * The Class JsonNodeLink.
 */
public class JsonNodeLink {

  protected String id;
  protected String source;
  protected String target;

  public String getId() {
    return id;
  }

  public void setId(String id) {
    this.id = id;
  }

  public String getSource() {
    return source;
  }

  public void setSource(String source) {
    this.source = source;
  }

  public String getTarget() {
    return target;
  }

  public void setTarget(String target) {
    this.target = target;
  }

  /* (non-Javadoc)
   * @see java.lang.Object#toString()
   */
  @Override
  public String toString() {
    return "JsonNodeLink [id=" + id + ", source=" + source + ", target=" + target + "]";
  }

}
27' href='#n527'>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 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647
/**
 * ============LICENSE_START=======================================================
 * org.onap.aai
 * ================================================================================
 * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
 * Copyright © 2017 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=========================================================
 *
 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
 */
package org.openecomp.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.openecomp.cl.api.Logger;
import org.openecomp.cl.eelf.LoggerFactory;
import org.openecomp.sparky.config.oxm.OxmEntityDescriptor;
import org.openecomp.sparky.config.oxm.OxmModelLoader;
import org.openecomp.sparky.dal.aai.ActiveInventoryDataProvider;
import org.openecomp.sparky.dal.aai.config.ActiveInventoryConfig;
import org.openecomp.sparky.dal.rest.OperationResult;
import org.openecomp.sparky.logging.AaiUiMsgs;
import org.openecomp.sparky.synchronizer.entity.SearchableEntity;
import org.openecomp.sparky.util.NodeUtils;
import org.openecomp.sparky.viewandinspect.config.TierSupportUiConstants;
import org.openecomp.sparky.viewandinspect.config.VisualizationConfig;
import org.openecomp.sparky.viewandinspect.entity.ActiveInventoryNode;
import org.openecomp.sparky.viewandinspect.entity.InlineMessage;
import org.openecomp.sparky.viewandinspect.entity.NodeProcessingTransaction;
import org.openecomp.sparky.viewandinspect.entity.QueryParams;
import org.openecomp.sparky.viewandinspect.entity.Relationship;
import org.openecomp.sparky.viewandinspect.entity.RelationshipData;
import org.openecomp.sparky.viewandinspect.entity.RelationshipList;
import org.openecomp.sparky.viewandinspect.entity.SelfLinkDeterminationTransaction;
import org.openecomp.sparky.viewandinspect.enumeration.NodeProcessingAction;
import org.openecomp.sparky.viewandinspect.enumeration.NodeProcessingState;
import org.openecomp.sparky.viewandinspect.task.PerformNodeSelfLinkProcessingTask;
import org.openecomp.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 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(
      VisualizationContext.class);
  private final ActiveInventoryDataProvider aaiProvider;

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

  private ActiveInventoryConfig aaiConfig;
  private VisualizationConfig visualizationConfig;
  private List<String> shallowEntities;

  private AtomicInteger totalLinksRetrieved;

  private final long contextId;
  private final String contextIdStr;

  private OxmModelLoader loader;
  private ObjectMapper mapper;
  private InlineMessage inlineMessage = null;

  private ExecutorService aaiExecutorService;

  /*
   * 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 VisualizationContext(long contextId, ActiveInventoryDataProvider aaiDataProvider,
      ExecutorService aaiExecutorService, OxmModelLoader loader) throws Exception {
    
    this.contextId = contextId;
    this.contextIdStr = "[Context-Id=" + contextId + "]";
    this.aaiProvider = aaiDataProvider;
    this.aaiExecutorService = aaiExecutorService;
    this.loader = loader;
    
    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.aaiConfig = ActiveInventoryConfig.getConfig();
    this.visualizationConfig = VisualizationConfig.getConfig();
    this.shallowEntities = aaiConfig.getAaiRestConfig().getShallowEntities();

    this.maxSelfLinkTraversalDepth = visualizationConfig.getMaxSelfLinkTraversalDepth();

    this.mapper = new ObjectMapper();
    mapper.setSerializationInclusion(Include.NON_EMPTY);
    mapper.setPropertyNamingStrategy(new PropertyNamingStrategy.KebabCaseStrategy());
  }
  
  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 = loader.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.getPrimaryKeyAttributeName();

          /*
           * 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();
            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 =
                aaiProvider.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, aaiProvider),
                aaiExecutorService).whenComplete((nodeTxn, error) -> {
                  aaiWorkOnHand.decrementAndGet();
                  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.isResolvedLinkFailure()) {
                        numFailedLinkResolve.incrementAndGet();
                      }

                      if (opResult.isResolvedLinkFromCache()) {
                        numSuccessfulLinkResolveFromCache.incrementAndGet();
                      }

                      if (opResult.isResolvedLinkFromServer()) {
                        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 = ActiveInventoryConfig.extractResourcePath(selfLink);

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

                        String uri = NodeUtils.calculateEditAttributeUri(selfLink);
                        if (uri != null) {
                          newChildNode.addProperty(TierSupportUiConstants.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);

                    }

                  }

                });

          }

          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 (loader.getEntityDescriptor(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 (loader.getEntityDescriptor(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(TierSupportUiConstants.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 (shallowEntities.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, aaiProvider, aaiConfig),
          aaiExecutorService).whenComplete((nodeTxn, error) -> {
            aaiWorkOnHand.decrementAndGet();
            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.isResolvedLinkFailure()) {
                  numFailedLinkResolve.incrementAndGet();
                }

                if (opResult.isResolvedLinkFromCache()) {
                  numSuccessfulLinkResolveFromCache.incrementAndGet();
                }

                if (opResult.isResolvedLinkFromServer()) {
                  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);

              }
            }

          });

    }

  }


  /**
   * 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 boolean findAndMarkRootNode(QueryParams queryParams) {

    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());
        return true;
      }
    }

    return false;

  }

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

    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 (!rootNodeDiscovered || cacheNode.getNodeDepth() < VisualizationConfig.getConfig()
              .getMaxSelfLinkTraversalDepth()) {

            if (LOG.isDebugEnabled()) {
              LOG.debug(AaiUiMsgs.DEBUG_GENERIC, 
                  "SLNC::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 (loader.getEntityDescriptor(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 =
        loader.getEntityDescriptor(ain.getEntityType()).getPrimaryKeyAttributeName();

    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;
    }

    OxmModelLoader modelLoader = OxmModelLoader.getInstance();

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

    if (relationshipArray != null) {

      ActiveInventoryNode newNode = null;
      String resourcePath = null;

      for (Relationship r : relationshipArray) {

        resourcePath = ActiveInventoryConfig.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();

        String entityType = r.getRelatedTo();

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

        descriptor = modelLoader.getEntityDescriptor(r.getRelatedTo());

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

        processingNode.addOutboundNeighbor(nodeId);

        if (descriptor != null) {

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

          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();

    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 (queryParams.getSearchTargetNodeId().equals(newNode.getNodeId())) {
      newNode.setNodeDepth(0);
      newNode.setRootNode(true);
      LOG.info(AaiUiMsgs.ROOT_NODE_DISCOVERED, queryParams.getSearchTargetNodeId());
    }

    newNode.setSelfLink(searchTargetEntity.getLink());

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

  /**
   * Checks for out standing work.
   *
   * @return true, if successful
   */
  private boolean hasOutStandingWork() {

    int numNodesWithPendingStates = 0;

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

    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() < VisualizationConfig.getConfig().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));

    return (numNodesWithPendingStates > 0);

  }

  /**
   * Process self links.
   *
   * @param skeletonNode the skeleton node
   * @param queryParams the query params
   */
  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;
      }

      processSearchableEntity(searchtargetEntity, queryParams);

      long startTimeInMs = System.currentTimeMillis();

      /*
       * wait until all transactions are complete or guard-timer expires.
       */

      long totalResolveTime = 0;
      boolean hasOutstandingWork = hasOutStandingWork();
      boolean outstandingWorkGuardTimerFired = false;
      long maxGuardTimeInMs = 5000;
      long guardTimeInMs = 0;
      boolean foundRootNode = false;

      
      /*
       * TODO:   Put a count-down-latch in place of the while loop, but if we do that then
       * we'll need to decouple the visualization processing from the main thread so it can continue to process while
       * the main thread is waiting on for count-down-latch gate to open.  This may also be easier once we move to the
       * VisualizationService + VisualizationContext ideas. 
       */
      
      
      while (hasOutstandingWork || !outstandingWorkGuardTimerFired) {

        if (!foundRootNode) {
          foundRootNode = findAndMarkRootNode(queryParams);
        }

        processCurrentNodeStates(foundRootNode);

        verifyOutboundNeighbors();

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

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

        if (!hasOutstandingWork) {

          guardTimeInMs += 500;

          if (guardTimeInMs > maxGuardTimeInMs) {
            outstandingWorkGuardTimerFired = true;
          }
        } else {
          guardTimeInMs = 0;
        }

        hasOutstandingWork = hasOutStandingWork();

      }

      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 (VisualizationConfig.getConfig().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 = loader.getEntityDescriptor(entityType);

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

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

    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, "/");

  }

}