@itentialopensource/adapter-firemon_securitymanager 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CALLS.md +4530 -0
  2. package/CHANGELOG.md +8 -1
  3. package/CONTRIBUTING.md +1 -160
  4. package/ENHANCE.md +2 -2
  5. package/README.md +32 -23
  6. package/SUMMARY.md +2 -2
  7. package/TROUBLESHOOT.md +6 -6
  8. package/adapter.js +162 -333
  9. package/adapterBase.js +541 -877
  10. package/changelogs/changelog.md +9 -0
  11. package/metadata.json +49 -0
  12. package/package.json +23 -25
  13. package/pronghorn.json +980 -641
  14. package/propertiesSchema.json +435 -35
  15. package/refs?service=git-upload-pack +0 -0
  16. package/report/adapter-openapi.json +63736 -0
  17. package/report/adapter-openapi.yaml +45622 -0
  18. package/report/adapterInfo.json +8 -8
  19. package/report/updateReport1691508716734.json +120 -0
  20. package/report/updateReport1692203173889.json +120 -0
  21. package/report/updateReport1694468126963.json +120 -0
  22. package/report/updateReport1698422536944.json +120 -0
  23. package/sampleProperties.json +63 -2
  24. package/test/integration/adapterTestBasicGet.js +2 -4
  25. package/test/integration/adapterTestConnectivity.js +91 -42
  26. package/test/integration/adapterTestIntegration.js +130 -2
  27. package/test/unit/adapterBaseTestUnit.js +388 -313
  28. package/test/unit/adapterTestUnit.js +304 -113
  29. package/utils/adapterInfo.js +1 -1
  30. package/utils/addAuth.js +1 -1
  31. package/utils/artifactize.js +1 -1
  32. package/utils/checkMigrate.js +1 -1
  33. package/utils/entitiesToDB.js +2 -2
  34. package/utils/findPath.js +1 -1
  35. package/utils/methodDocumentor.js +273 -0
  36. package/utils/modify.js +13 -15
  37. package/utils/packModificationScript.js +1 -1
  38. package/utils/pre-commit.sh +2 -0
  39. package/utils/taskMover.js +309 -0
  40. package/utils/tbScript.js +89 -34
  41. package/utils/tbUtils.js +41 -21
  42. package/utils/testRunner.js +1 -1
  43. package/utils/troubleshootingAdapter.js +9 -6
  44. package/workflows/README.md +0 -3
package/adapterBase.js CHANGED
@@ -11,14 +11,18 @@
11
11
  /* eslint prefer-destructuring: warn */
12
12
 
13
13
  /* Required libraries. */
14
- const fs = require('fs-extra');
15
14
  const path = require('path');
16
- const jsonQuery = require('json-query');
17
- const EventEmitterCl = require('events').EventEmitter;
18
15
  const { execSync } = require('child_process');
16
+ const { spawnSync } = require('child_process');
17
+ const EventEmitterCl = require('events').EventEmitter;
18
+ const fs = require('fs-extra');
19
+ const jsonQuery = require('json-query');
20
+
21
+ const sampleProperties = require(`${__dirname}/sampleProperties.json`).properties;
19
22
 
20
23
  /* The schema validator */
21
24
  const AjvCl = require('ajv');
25
+ const { Test } = require('mocha');
22
26
 
23
27
  /* Fetch in the other needed components for the this Adaptor */
24
28
  const PropUtilCl = require('@itentialopensource/adapter-utils').PropertyUtility;
@@ -27,8 +31,10 @@ const RequestHandlerCl = require('@itentialopensource/adapter-utils').RequestHan
27
31
  const entitiesToDB = require(path.join(__dirname, 'utils/entitiesToDB'));
28
32
  const troubleshootingAdapter = require(path.join(__dirname, 'utils/troubleshootingAdapter'));
29
33
  const tbUtils = require(path.join(__dirname, 'utils/tbUtils'));
34
+ const taskMover = require(path.join(__dirname, 'utils/taskMover'));
30
35
 
31
36
  let propUtil = null;
37
+ let choosepath = null;
32
38
 
33
39
  /*
34
40
  * INTERNAL FUNCTION: force fail the adapter - generally done to cause restart
@@ -101,7 +107,7 @@ function updateSchema(entityPath, configFile, changes) {
101
107
  /*
102
108
  * INTERNAL FUNCTION: update the mock data file
103
109
  */
104
- function updateMock(mockPath, configFile, changes) {
110
+ function updateMock(mockPath, configFile, changes, replace) {
105
111
  // if the mock file does not exist - create it
106
112
  const mockFile = path.join(mockPath, `/${configFile}`);
107
113
  if (!fs.existsSync(mockFile)) {
@@ -113,7 +119,11 @@ function updateMock(mockPath, configFile, changes) {
113
119
  let mock = require(path.resolve(mockPath, configFile));
114
120
 
115
121
  // merge the changes into the mock file
116
- mock = propUtil.mergeProperties(changes, mock);
122
+ if (replace === true) {
123
+ mock = changes;
124
+ } else {
125
+ mock = propUtil.mergeProperties(changes, mock);
126
+ }
117
127
 
118
128
  fs.writeFileSync(mockFile, JSON.stringify(mock, null, 2));
119
129
  return null;
@@ -145,27 +155,6 @@ function updatePackage(changes) {
145
155
  return null;
146
156
  }
147
157
 
148
- /*
149
- * INTERNAL FUNCTION: get data from source(s) - nested
150
- */
151
- function getDataFromSources(loopField, sources) {
152
- let fieldValue = loopField;
153
-
154
- // go through the sources to find the field
155
- for (let s = 0; s < sources.length; s += 1) {
156
- // find the field value using jsonquery
157
- const nestedValue = jsonQuery(loopField, { data: sources[s] }).value;
158
-
159
- // if we found in source - set and no need to check other sources
160
- if (nestedValue) {
161
- fieldValue = nestedValue;
162
- break;
163
- }
164
- }
165
-
166
- return fieldValue;
167
- }
168
-
169
158
  /* GENERAL ADAPTER FUNCTIONS THESE SHOULD NOT BE DIRECTLY MODIFIED */
170
159
  /* IF YOU NEED MODIFICATIONS, REDEFINE THEM IN adapter.js!!! */
171
160
  class AdapterBase extends EventEmitterCl {
@@ -255,7 +244,7 @@ class AdapterBase extends EventEmitterCl {
255
244
  this.allProps = this.propUtilInst.mergeProperties(properties, defProps);
256
245
 
257
246
  // validate the entity against the schema
258
- const ajvInst = new AjvCl();
247
+ const ajvInst = new AjvCl({ strictSchema: false, allowUnionTypes: true });
259
248
  const validate = ajvInst.compile(propertiesSchema);
260
249
  const result = validate(this.allProps);
261
250
 
@@ -433,6 +422,40 @@ class AdapterBase extends EventEmitterCl {
433
422
  return myfunctions;
434
423
  }
435
424
 
425
+ /**
426
+ * iapGetAdapterWorkflowFunctions is used to get all of the workflow function in the adapter
427
+ * @param {array} ignoreThese - additional methods to ignore (optional)
428
+ *
429
+ * @function iapGetAdapterWorkflowFunctions
430
+ */
431
+ iapGetAdapterWorkflowFunctions(ignoreThese) {
432
+ const myfunctions = this.getAllFunctions();
433
+ const wffunctions = [];
434
+
435
+ // remove the functions that should not be in a Workflow
436
+ for (let m = 0; m < myfunctions.length; m += 1) {
437
+ if (myfunctions[m] === 'checkActionFiles') {
438
+ // got to the second tier (adapterBase)
439
+ break;
440
+ }
441
+ if (!(myfunctions[m].endsWith('Emit') || myfunctions[m].match(/Emit__v[0-9]+/))) {
442
+ let found = false;
443
+ if (ignoreThese && Array.isArray(ignoreThese)) {
444
+ for (let i = 0; i < ignoreThese.length; i += 1) {
445
+ if (myfunctions[m].toUpperCase() === ignoreThese[i].toUpperCase()) {
446
+ found = true;
447
+ }
448
+ }
449
+ }
450
+ if (!found) {
451
+ wffunctions.push(myfunctions[m]);
452
+ }
453
+ }
454
+ }
455
+
456
+ return wffunctions;
457
+ }
458
+
436
459
  /**
437
460
  * checkActionFiles is used to update the validation of the action files.
438
461
  *
@@ -488,40 +511,6 @@ class AdapterBase extends EventEmitterCl {
488
511
  return this.requestHandlerInst.encryptProperty(property, technique, callback);
489
512
  }
490
513
 
491
- /**
492
- * iapGetAdapterWorkflowFunctions is used to get all of the workflow function in the adapter
493
- * @param {array} ignoreThese - additional methods to ignore (optional)
494
- *
495
- * @function iapGetAdapterWorkflowFunctions
496
- */
497
- iapGetAdapterWorkflowFunctions(ignoreThese) {
498
- const myfunctions = this.getAllFunctions();
499
- const wffunctions = [];
500
-
501
- // remove the functions that should not be in a Workflow
502
- for (let m = 0; m < myfunctions.length; m += 1) {
503
- if (myfunctions[m] === 'addEntityCache') {
504
- // got to the second tier (adapterBase)
505
- break;
506
- }
507
- if (!(myfunctions[m].endsWith('Emit') || myfunctions[m].match(/Emit__v[0-9]+/))) {
508
- let found = false;
509
- if (ignoreThese && Array.isArray(ignoreThese)) {
510
- for (let i = 0; i < ignoreThese.length; i += 1) {
511
- if (myfunctions[m].toUpperCase() === ignoreThese[i].toUpperCase()) {
512
- found = true;
513
- }
514
- }
515
- }
516
- if (!found) {
517
- wffunctions.push(myfunctions[m]);
518
- }
519
- }
520
- }
521
-
522
- return wffunctions;
523
- }
524
-
525
514
  /**
526
515
  * iapUpdateAdapterConfiguration is used to update any of the adapter configuration files. This
527
516
  * allows customers to make changes to adapter configuration without having to be on the
@@ -533,16 +522,17 @@ class AdapterBase extends EventEmitterCl {
533
522
  * @param {string} entity - the entity to be changed, if an action, schema or mock data file (optional)
534
523
  * @param {string} type - the type of entity file to change, (action, schema, mock) (optional)
535
524
  * @param {string} action - the action to be changed, if an action, schema or mock data file (optional)
525
+ * @param {boolean} replace - true to replace entire mock data, false to merge/append (optional)
536
526
  * @param {Callback} callback - The results of the call
537
527
  */
538
- iapUpdateAdapterConfiguration(configFile, changes, entity, type, action, callback) {
528
+ iapUpdateAdapterConfiguration(configFile, changes, entity, type, action, replace, callback) {
539
529
  const meth = 'adapterBase-iapUpdateAdapterConfiguration';
540
530
  const origin = `${this.id}-${meth}`;
541
531
  log.trace(origin);
542
532
 
543
533
  // verify the parameters are valid
544
534
  if (changes === undefined || changes === null || typeof changes !== 'object'
545
- || Object.keys(changes).length === 0) {
535
+ || Object.keys(changes).length === 0) {
546
536
  const result = {
547
537
  response: 'No configuration updates to make'
548
538
  };
@@ -627,8 +617,14 @@ class AdapterBase extends EventEmitterCl {
627
617
  if (!fs.existsSync(mpath)) {
628
618
  fs.mkdirSync(mpath);
629
619
  }
620
+ // this means we are changing a mock data file so replace is required
621
+ if (replace === undefined || replace === null || replace === '') {
622
+ const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Missing Data', ['replace'], null, null, null);
623
+ log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
624
+ return callback(null, errorObj);
625
+ }
626
+ const mres = updateMock(mpath, configFile, changes, replace);
630
627
 
631
- const mres = updateMock(mpath, configFile, changes);
632
628
  if (mres) {
633
629
  const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, `Incomplete Configuration Change: ${mres}`, [], null, null, null);
634
630
  log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
@@ -645,6 +641,86 @@ class AdapterBase extends EventEmitterCl {
645
641
  return callback(null, errorObj);
646
642
  }
647
643
 
644
+ /**
645
+ * @summary Suspends the adapter
646
+ * @param {Callback} callback - The adapater suspension status
647
+ * @function iapSuspendAdapter
648
+ */
649
+ iapSuspendAdapter(mode, callback) {
650
+ const origin = `${this.id}-adapterBase-iapSuspendAdapter`;
651
+ if (this.suspended) {
652
+ throw new Error(`${origin}: Adapter is already suspended`);
653
+ }
654
+ try {
655
+ this.suspended = true;
656
+ this.suspendMode = mode;
657
+ if (this.suspendMode === 'pause') {
658
+ const props = JSON.parse(JSON.stringify(this.initProps));
659
+ // To suspend adapter, enable throttling and set concurrent max to 0
660
+ props.throttle.throttle_enabled = true;
661
+ props.throttle.concurrent_max = 0;
662
+ this.refreshProperties(props);
663
+ }
664
+ return callback({ suspended: true });
665
+ } catch (error) {
666
+ return callback(null, error);
667
+ }
668
+ }
669
+
670
+ /**
671
+ * @summary Unsuspends the adapter
672
+ * @param {Callback} callback - The adapater suspension status
673
+ *
674
+ * @function iapUnsuspendAdapter
675
+ */
676
+ iapUnsuspendAdapter(callback) {
677
+ const origin = `${this.id}-adapterBase-iapUnsuspendAdapter`;
678
+ if (!this.suspended) {
679
+ throw new Error(`${origin}: Adapter is not suspended`);
680
+ }
681
+ if (this.suspendMode === 'pause') {
682
+ const props = JSON.parse(JSON.stringify(this.initProps));
683
+ // To unsuspend adapter, keep throttling enabled and begin processing queued requests in order
684
+ props.throttle.throttle_enabled = true;
685
+ props.throttle.concurrent_max = 1;
686
+ this.refreshProperties(props);
687
+ setTimeout(() => {
688
+ this.getQueue((q, error) => {
689
+ // console.log("Items in queue: " + String(q.length))
690
+ if (q.length === 0) {
691
+ // if queue is empty, return to initial properties state
692
+ this.refreshProperties(this.initProps);
693
+ this.suspended = false;
694
+ return callback({ suspended: false });
695
+ }
696
+ // recursive call to check queue again every second
697
+ return this.iapUnsuspendAdapter(callback);
698
+ });
699
+ }, 1000);
700
+ } else {
701
+ this.suspended = false;
702
+ callback({ suspend: false });
703
+ }
704
+ }
705
+
706
+ /**
707
+ * iapGetAdapterQueue is used to get information for all of the requests currently in the queue.
708
+ *
709
+ * @function iapGetAdapterQueue
710
+ * @param {Callback} callback - a callback function to return the result (Queue) or the error
711
+ */
712
+ iapGetAdapterQueue(callback) {
713
+ const origin = `${this.id}-adapterBase-iapGetAdapterQueue`;
714
+ log.trace(origin);
715
+
716
+ return this.requestHandlerInst.getQueue(callback);
717
+ }
718
+
719
+ /* ********************************************** */
720
+ /* */
721
+ /* EXPOSES ADAPTER SCRIPTS */
722
+ /* */
723
+ /* ********************************************** */
648
724
  /**
649
725
  * See if the API path provided is found in this adapter
650
726
  *
@@ -665,6 +741,10 @@ class AdapterBase extends EventEmitterCl {
665
741
  return callback(null, result);
666
742
  }
667
743
 
744
+ if (typeof this.allProps.choosepath === 'string') {
745
+ choosepath = this.allProps.choosepath;
746
+ }
747
+
668
748
  // make sure the entities directory exists
669
749
  const entitydir = path.join(__dirname, 'entities');
670
750
  if (!fs.statSync(entitydir).isDirectory()) {
@@ -689,7 +769,25 @@ class AdapterBase extends EventEmitterCl {
689
769
 
690
770
  // go through all of the actions set the appropriate info in the newActions
691
771
  for (let a = 0; a < actions.actions.length; a += 1) {
692
- if (actions.actions[a].entitypath.indexOf(apiPath) >= 0) {
772
+ if (actions.actions[a].entitypath && typeof actions.actions[a].entitypath === 'object') {
773
+ const entityKeys = Object.keys(actions.actions[a].entitypath);
774
+ if (entityKeys.length > 0) {
775
+ for (let entityKey = 0; entityKey < entityKeys.length; entityKey += 1) {
776
+ if (choosepath && entityKeys[entityKey] === choosepath && actions.actions[a].entitypath[entityKeys[entityKey]].indexOf(apiPath) >= 0) {
777
+ log.info(` Found - entity: ${entities[e]} action: ${actions.actions[a].name}`);
778
+ log.info(` method: ${actions.actions[a].method} path: ${actions.actions[a].entitypath[entityKeys[entityKey]]}`);
779
+ const fitem = {
780
+ entity: entities[e],
781
+ action: actions.actions[a].name,
782
+ method: actions.actions[a].method,
783
+ path: actions.actions[a].entitypath[entityKeys[entityKey]]
784
+ };
785
+ fitems.push(fitem);
786
+ break;
787
+ }
788
+ }
789
+ }
790
+ } else if (actions.actions[a].entitypath.indexOf(apiPath) >= 0) {
693
791
  log.info(` Found - entity: ${entities[e]} action: ${actions.actions[a].name}`);
694
792
  log.info(` method: ${actions.actions[a].method} path: ${actions.actions[a].entitypath}`);
695
793
  const fitem = {
@@ -728,81 +826,6 @@ class AdapterBase extends EventEmitterCl {
728
826
  return callback(result, null);
729
827
  }
730
828
 
731
- /**
732
- * @summary Suspends the adapter
733
- * @param {Callback} callback - The adapater suspension status
734
- * @function iapSuspendAdapter
735
- */
736
- iapSuspendAdapter(mode, callback) {
737
- const origin = `${this.id}-adapterBase-iapSuspendAdapter`;
738
- if (this.suspended) {
739
- throw new Error(`${origin}: Adapter is already suspended`);
740
- }
741
- try {
742
- this.suspended = true;
743
- this.suspendMode = mode;
744
- if (this.suspendMode === 'pause') {
745
- const props = JSON.parse(JSON.stringify(this.initProps));
746
- // To suspend adapter, enable throttling and set concurrent max to 0
747
- props.throttle.throttle_enabled = true;
748
- props.throttle.concurrent_max = 0;
749
- this.refreshProperties(props);
750
- }
751
- return callback({ suspended: true });
752
- } catch (error) {
753
- return callback(null, error);
754
- }
755
- }
756
-
757
- /**
758
- * @summary Unsuspends the adapter
759
- * @param {Callback} callback - The adapater suspension status
760
- *
761
- * @function iapUnsuspendAdapter
762
- */
763
- iapUnsuspendAdapter(callback) {
764
- const origin = `${this.id}-adapterBase-iapUnsuspendAdapter`;
765
- if (!this.suspended) {
766
- throw new Error(`${origin}: Adapter is not suspended`);
767
- }
768
- if (this.suspendMode === 'pause') {
769
- const props = JSON.parse(JSON.stringify(this.initProps));
770
- // To unsuspend adapter, keep throttling enabled and begin processing queued requests in order
771
- props.throttle.throttle_enabled = true;
772
- props.throttle.concurrent_max = 1;
773
- this.refreshProperties(props);
774
- setTimeout(() => {
775
- this.getQueue((q, error) => {
776
- // console.log("Items in queue: " + String(q.length))
777
- if (q.length === 0) {
778
- // if queue is empty, return to initial properties state
779
- this.refreshProperties(this.initProps);
780
- this.suspended = false;
781
- return callback({ suspended: false });
782
- }
783
- // recursive call to check queue again every second
784
- return this.iapUnsuspendAdapter(callback);
785
- });
786
- }, 1000);
787
- } else {
788
- this.suspended = false;
789
- callback({ suspend: false });
790
- }
791
- }
792
-
793
- /**
794
- * iapGetAdapterQueue is used to get information for all of the requests currently in the queue.
795
- *
796
- * @function iapGetAdapterQueue
797
- * @param {Callback} callback - a callback function to return the result (Queue) or the error
798
- */
799
- iapGetAdapterQueue(callback) {
800
- const origin = `${this.id}-adapterBase-iapGetAdapterQueue`;
801
- log.trace(origin);
802
-
803
- return this.requestHandlerInst.getQueue(callback);
804
- }
805
-
806
829
  /**
807
830
  * @summary runs troubleshoot scripts for adapter
808
831
  *
@@ -837,7 +860,7 @@ class AdapterBase extends EventEmitterCl {
837
860
  if (result) {
838
861
  return callback(result);
839
862
  }
840
- return callback(null, result);
863
+ return callback(null, 'Healthcheck failed');
841
864
  } catch (error) {
842
865
  return callback(null, error);
843
866
  }
@@ -852,8 +875,7 @@ class AdapterBase extends EventEmitterCl {
852
875
  */
853
876
  async iapRunAdapterConnectivity(callback) {
854
877
  try {
855
- const { serviceItem } = await tbUtils.getAdapterConfig();
856
- const { host } = serviceItem.properties.properties;
878
+ const { host } = this.allProps;
857
879
  const result = tbUtils.runConnectivity(host, false);
858
880
  if (result.failCount > 0) {
859
881
  return callback(null, result);
@@ -905,156 +927,89 @@ class AdapterBase extends EventEmitterCl {
905
927
  }
906
928
 
907
929
  /**
908
- * @summary take the entities and add them to the cache
909
- *
910
- * @function addEntityCache
911
- * @param {String} entityType - the type of the entities
912
- * @param {Array} data - the list of entities
913
- * @param {String} key - unique key for the entities
930
+ * @function iapDeactivateTasks
914
931
  *
915
- * @param {Callback} callback - An array of whether the adapter can has the
916
- * desired capability or an error
932
+ * @param {Array} tasks - List of tasks to deactivate
933
+ * @param {Callback} callback
917
934
  */
918
- addEntityCache(entityType, entities, key, callback) {
919
- const meth = 'adapterBase-addEntityCache';
935
+ iapDeactivateTasks(tasks, callback) {
936
+ const meth = 'adapterBase-iapDeactivateTasks';
920
937
  const origin = `${this.id}-${meth}`;
921
938
  log.trace(origin);
922
-
923
- // list containing the items to add to the cache
924
- const entityIds = [];
925
-
926
- if (entities && Object.hasOwnProperty.call(entities, 'response')
927
- && Array.isArray(entities.response)) {
928
- for (let e = 0; e < entities.response.length; e += 1) {
929
- entityIds.push(entities.response[e][key]);
930
- }
939
+ let data;
940
+ try {
941
+ data = taskMover.deactivateTasks(__dirname, tasks);
942
+ } catch (ex) {
943
+ taskMover.rollbackChanges(__dirname);
944
+ taskMover.deleteBackups(__dirname);
945
+ return callback(null, ex);
931
946
  }
932
-
933
- // add the entities to the cache
934
- return this.requestHandlerInst.addEntityCache(entityType, entityIds, (loaded, error) => {
935
- if (error) {
936
- return callback(null, error);
937
- }
938
- if (!loaded) {
939
- const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Entity Cache Not Loading', [entityType], null, null, null);
940
- log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
941
- return callback(null, errorObj);
942
- }
943
-
944
- return callback(loaded);
945
- });
946
- }
947
+ taskMover.deleteBackups(__dirname);
948
+ return callback(data, null);
949
+ }
947
950
 
948
951
  /**
949
- * @summary sees if the entity is in the entity list or not
952
+ * @function iapActivateTasks
950
953
  *
951
- * @function entityInList
952
- * @param {String/Array} entityId - the specific entity we are looking for
953
- * @param {Array} data - the list of entities
954
- *
955
- * @param {Callback} callback - An array of whether the adapter can has the
956
- * desired capability or an error
954
+ * @param {Array} tasks - List of tasks to deactivate
955
+ * @param {Callback} callback
957
956
  */
958
- entityInList(entityId, data) {
959
- const origin = `${this.id}-adapterBase-entityInList`;
957
+ iapActivateTasks(tasks, callback) {
958
+ const meth = 'adapterBase-iapActivateTasks';
959
+ const origin = `${this.id}-${meth}`;
960
960
  log.trace(origin);
961
-
962
- // need to check on the entities that were passed in
963
- if (Array.isArray(entityId)) {
964
- const resEntity = [];
965
-
966
- for (let e = 0; e < entityId.length; e += 1) {
967
- if (data.includes(entityId[e])) {
968
- resEntity.push(true);
969
- } else {
970
- resEntity.push(false);
971
- }
972
- }
973
-
974
- return resEntity;
961
+ let data;
962
+ try {
963
+ data = taskMover.activateTasks(__dirname, tasks);
964
+ } catch (ex) {
965
+ taskMover.rollbackChanges(__dirname);
966
+ taskMover.deleteBackups(__dirname);
967
+ return callback(null, ex);
975
968
  }
976
-
977
- // does the entity list include the specific entity
978
- return [data.includes(entityId)];
969
+ taskMover.deleteBackups(__dirname);
970
+ return callback(data, null);
979
971
  }
980
972
 
973
+ /* ********************************************** */
974
+ /* */
975
+ /* EXPOSES CACHE CALLS */
976
+ /* */
977
+ /* ********************************************** */
981
978
  /**
982
- * @summary prepare results for verify capability so they are true/false
979
+ * @summary Populate the cache for the given entities
983
980
  *
984
- * @function capabilityResults
985
- * @param {Array} results - the results from the capability check
986
- *
987
- * @param {Callback} callback - An array of whether the adapter can has the
988
- * desired capability or an error
981
+ * @function iapPopulateEntityCache
982
+ * @param {String/Array of Strings} entityType - the entity type(s) to populate
983
+ * @param {Callback} callback - whether the cache was updated or not for each entity type
984
+ * @returns return of the callback
989
985
  */
990
- capabilityResults(results, callback) {
991
- const meth = 'adapterBase-capabilityResults';
992
- const origin = `${this.id}-${meth}`;
986
+ iapPopulateEntityCache(entityTypes, callback) {
987
+ const origin = `${this.myid}-adapterBase-iapPopulateEntityCache`;
993
988
  log.trace(origin);
994
- let locResults = results;
995
-
996
- if (locResults && locResults[0] === 'needupdate') {
997
- const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Entity Cache Not Loading', ['unknown'], null, null, null);
998
- log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
999
- this.repeatCacheCount += 1;
1000
- return callback(null, errorObj);
1001
- }
1002
-
1003
- // if an error occured, return the error
1004
- if (locResults && locResults[0] === 'error') {
1005
- const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Error Verifying Entity Cache', null, null, null, null);
1006
- log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1007
- return callback(null, errorObj);
1008
- }
1009
-
1010
- // go through the response and change to true/false
1011
- if (locResults) {
1012
- // if not an array, just convert the return
1013
- if (!Array.isArray(locResults)) {
1014
- if (locResults === 'found') {
1015
- locResults = [true];
1016
- } else {
1017
- locResults = [false];
1018
- }
1019
- } else {
1020
- const temp = [];
1021
-
1022
- // go through each element in the array to convert
1023
- for (let r = 0; r < locResults.length; r += 1) {
1024
- if (locResults[r] === 'found') {
1025
- temp.push(true);
1026
- } else {
1027
- temp.push(false);
1028
- }
1029
- }
1030
- locResults = temp;
1031
- }
1032
- }
1033
989
 
1034
- // return the results
1035
- return callback(locResults);
990
+ return this.requestHandlerInst.populateEntityCache(entityTypes, callback);
1036
991
  }
1037
992
 
1038
993
  /**
1039
- * @summary Provides a way for the adapter to tell north bound integrations
1040
- * all of the capabilities for the current adapter
1041
- *
1042
- * @function getAllCapabilities
994
+ * @summary Retrieves data from cache for specified entity type
1043
995
  *
1044
- * @return {Array} - containing the entities and the actions available on each entity
996
+ * @function iapRetrieveEntitiesCache
997
+ * @param {String} entityType - entity of which to retrieve
998
+ * @param {Object} options - settings of which data to return and how to return it
999
+ * @param {Callback} callback - the data if it was retrieved
1045
1000
  */
1046
- getAllCapabilities() {
1047
- const origin = `${this.id}-adapterBase-getAllCapabilities`;
1001
+ iapRetrieveEntitiesCache(entityType, options, callback) {
1002
+ const origin = `${this.myid}-adapterBase-iapRetrieveEntitiesCache`;
1048
1003
  log.trace(origin);
1049
1004
 
1050
- // validate the capabilities for the adapter
1051
- try {
1052
- return this.requestHandlerInst.getAllCapabilities();
1053
- } catch (e) {
1054
- return [];
1055
- }
1005
+ return this.requestHandlerInst.retrieveEntitiesCache(entityType, options, callback);
1056
1006
  }
1057
1007
 
1008
+ /* ********************************************** */
1009
+ /* */
1010
+ /* EXPOSES BROKER CALLS */
1011
+ /* */
1012
+ /* ********************************************** */
1058
1013
  /**
1059
1014
  * @summary Determines if this adapter supports any in a list of entities
1060
1015
  *
@@ -1066,396 +1021,61 @@ class AdapterBase extends EventEmitterCl {
1066
1021
  * value is true or false
1067
1022
  */
1068
1023
  hasEntities(entityType, entityList, callback) {
1069
- const origin = `${this.id}-adapter-hasEntities`;
1024
+ const origin = `${this.id}-adapterBase-hasEntities`;
1070
1025
  log.trace(origin);
1071
1026
 
1072
- switch (entityType) {
1073
- case 'Device':
1074
- return this.hasDevices(entityList, callback);
1075
- default:
1076
- return callback(null, `${this.id} does not support entity ${entityType}`);
1077
- }
1027
+ return this.requestHandlerInst.hasEntities(entityType, entityList, callback);
1078
1028
  }
1079
1029
 
1080
1030
  /**
1081
- * @summary Helper method for hasEntities for the specific device case
1031
+ * @summary Determines if this adapter supports any in a list of entities
1082
1032
  *
1083
- * @param {Array} deviceList - array of unique device identifiers
1084
- * @param {Callback} callback - A map where the device is the key and the
1033
+ * @function hasEntitiesAuth
1034
+ * @param {String} entityType - the entity type to check for
1035
+ * @param {Array} entityList - the list of entities we are looking for
1036
+ * @param {Object} callOptions - Additional options used to make request, including auth headers, AWS service, or datatypes
1037
+ *
1038
+ * @param {Callback} callback - A map where the entity is the key and the
1085
1039
  * value is true or false
1086
1040
  */
1087
- hasDevices(deviceList, callback) {
1088
- const origin = `${this.id}-adapter-hasDevices`;
1041
+ hasEntitiesAuth(entityType, entityList, callOptions, callback) {
1042
+ const origin = `${this.id}-adapterBase-hasEntitiesAuth`;
1089
1043
  log.trace(origin);
1090
1044
 
1091
- const findings = deviceList.reduce((map, device) => {
1092
- // eslint-disable-next-line no-param-reassign
1093
- map[device] = false;
1094
- log.debug(`In reduce: ${JSON.stringify(map)}`);
1095
- return map;
1096
- }, {});
1097
- const apiCalls = deviceList.map((device) => new Promise((resolve) => {
1098
- this.getDevice(device, (result, error) => {
1099
- if (error) {
1100
- log.debug(`In map error: ${JSON.stringify(device)}`);
1101
- return resolve({ name: device, found: false });
1102
- }
1103
- log.debug(`In map: ${JSON.stringify(device)}`);
1104
- return resolve({ name: device, found: true });
1105
- });
1106
- }));
1107
- Promise.all(apiCalls).then((results) => {
1108
- results.forEach((device) => {
1109
- findings[device.name] = device.found;
1110
- });
1111
- log.debug(`FINDINGS: ${JSON.stringify(findings)}`);
1112
- return callback(findings);
1113
- }).catch((errors) => {
1114
- log.error('Unable to do device lookup.');
1115
- return callback(null, { code: 503, message: 'Unable to do device lookup.', error: errors });
1116
- });
1045
+ return this.requestHandlerInst.hasEntitiesAuth(entityType, entityList, callOptions, callback);
1117
1046
  }
1118
1047
 
1119
1048
  /**
1120
- * @summary Make one of the needed Broker calls - could be one of many
1049
+ * @summary Get Appliance that match the deviceName
1121
1050
  *
1122
- * @function iapMakeBrokerCall
1123
- * @param {string} brokCall - the name of the broker call (required)
1124
- * @param {object} callProps - the proeprties for the broker call (required)
1125
- * @param {object} devResp - the device details to extract needed inputs (required)
1126
- * @param {string} filterName - any filter to search on (required)
1051
+ * @function getDevice
1052
+ * @param {String} deviceName - the deviceName to find (required)
1127
1053
  *
1128
- * @param {getCallback} callback - a callback function to return the result of the call
1054
+ * @param {getCallback} callback - a callback function to return the result
1055
+ * (appliance) or the error
1129
1056
  */
1130
- iapMakeBrokerCall(brokCall, callProps, devResp, filterName, callback) {
1131
- const meth = 'adapterBase-iapMakeBrokerCall';
1132
- const origin = `${this.id}-${meth}`;
1057
+ getDevice(deviceName, callback) {
1058
+ const origin = `${this.id}-adapterBase-getDevice`;
1133
1059
  log.trace(origin);
1134
1060
 
1135
- try {
1136
- let uriPath = '';
1137
- let uriMethod = 'GET';
1138
- let callQuery = {};
1139
- let callBody = {};
1140
- let callHeaders = {};
1141
- let handleFail = 'fail';
1142
- let ostypePrefix = '';
1143
- let statusValue = 'true';
1144
- if (callProps.path) {
1145
- uriPath = `${callProps.path}`;
1146
-
1147
- // make any necessary changes to the path
1148
- if (devResp !== null && callProps.requestFields && Object.keys(callProps.requestFields).length > 0) {
1149
- const rqKeys = Object.keys(callProps.requestFields);
1150
-
1151
- // get the field from the provided device
1152
- for (let rq = 0; rq < rqKeys.length; rq += 1) {
1153
- const fieldValue = getDataFromSources(callProps.requestFields[rqKeys[rq]], devResp);
1154
-
1155
- // put the value into the path - if it has been specified in the path
1156
- uriPath = uriPath.replace(`{${rqKeys[rq]}}`, fieldValue);
1157
- }
1158
- }
1159
- }
1160
- if (callProps.method) {
1161
- uriMethod = callProps.method;
1162
- }
1163
- if (callProps.query) {
1164
- callQuery = callProps.query;
1165
-
1166
- // go through the query params to check for variable values
1167
- const cpKeys = Object.keys(callQuery);
1168
- for (let cp = 0; cp < cpKeys.length; cp += 1) {
1169
- if (callQuery[cpKeys[cp]].startsWith('{') && callQuery[cpKeys[cp]].endsWith('}')) {
1170
- // make any necessary changes to the query params
1171
- if (devResp !== null && callProps.requestFields && Object.keys(callProps.requestFields).length > 0) {
1172
- const rqKeys = Object.keys(callProps.requestFields);
1173
-
1174
- // get the field from the provided device
1175
- for (let rq = 0; rq < rqKeys.length; rq += 1) {
1176
- if (cpKeys[cp] === rqKeys[rq]) {
1177
- const fieldValue = getDataFromSources(callProps.requestFields[rqKeys[rq]], devResp);
1178
-
1179
- // put the value into the query - if it has been specified in the query
1180
- callQuery[cpKeys[cp]] = fieldValue;
1181
- }
1182
- }
1183
- }
1184
- }
1185
- }
1186
- }
1187
- if (callProps.body) {
1188
- callBody = callProps.body;
1189
-
1190
- // go through the body fields to check for variable values
1191
- const cbKeys = Object.keys(callBody);
1192
- for (let cb = 0; cb < cbKeys.length; cb += 1) {
1193
- if (callBody[cbKeys[cb]].startsWith('{') && callBody[cbKeys[cb]].endsWith('}')) {
1194
- // make any necessary changes to the query params
1195
- if (devResp !== null && callProps.requestFields && Object.keys(callProps.requestFields).length > 0) {
1196
- const rqKeys = Object.keys(callProps.requestFields);
1197
-
1198
- // get the field from the provided device
1199
- for (let rq = 0; rq < rqKeys.length; rq += 1) {
1200
- if (cbKeys[cb] === rqKeys[rq]) {
1201
- const fieldValue = getDataFromSources(callProps.requestFields[rqKeys[rq]], devResp);
1202
-
1203
- // put the value into the query - if it has been specified in the query
1204
- callBody[cbKeys[cb]] = fieldValue;
1205
- }
1206
- }
1207
- }
1208
- }
1209
- }
1210
- }
1211
- if (callProps.headers) {
1212
- callHeaders = callProps.headers;
1213
-
1214
- // go through the body fields to check for variable values
1215
- const chKeys = Object.keys(callHeaders);
1216
- for (let ch = 0; ch < chKeys.length; ch += 1) {
1217
- if (callHeaders[chKeys[ch]].startsWith('{') && callHeaders[chKeys[ch]].endsWith('}')) {
1218
- // make any necessary changes to the query params
1219
- if (devResp !== null && callProps.requestFields && Object.keys(callProps.requestFields).length > 0) {
1220
- const rqKeys = Object.keys(callProps.requestFields);
1221
-
1222
- // get the field from the provided device
1223
- for (let rq = 0; rq < rqKeys.length; rq += 1) {
1224
- if (chKeys[ch] === rqKeys[rq]) {
1225
- const fieldValue = getDataFromSources(callProps.requestFields[rqKeys[rq]], devResp);
1226
-
1227
- // put the value into the query - if it has been specified in the query
1228
- callHeaders[chKeys[ch]] = fieldValue;
1229
- }
1230
- }
1231
- }
1232
- }
1233
- }
1234
- }
1235
- if (callProps.handleFailure) {
1236
- handleFail = callProps.handleFailure;
1237
- }
1238
- if (callProps.responseFields && callProps.responseFields.ostypePrefix) {
1239
- ostypePrefix = callProps.responseFields.ostypePrefix;
1240
- }
1241
- if (callProps.responseFields && callProps.responseFields.statusValue) {
1242
- statusValue = callProps.responseFields.statusValue;
1243
- }
1244
-
1245
- // !! using Generic makes it easier on the Adapter Builder (just need to change the path)
1246
- // !! you can also replace with a specific call if that is easier
1247
- return this.genericAdapterRequest(uriPath, uriMethod, callQuery, callBody, callHeaders, (result, error) => {
1248
- // if we received an error or their is no response on the results return an error
1249
- if (error) {
1250
- if (handleFail === 'fail') {
1251
- return callback(null, error);
1252
- }
1253
- return callback({}, null);
1254
- }
1255
- if (!result.response) {
1256
- if (handleFail === 'fail') {
1257
- const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Invalid Response', [brokCall], null, null, null);
1258
- log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1259
- return callback(null, errorObj);
1260
- }
1261
- return callback({}, null);
1262
- }
1263
-
1264
- // get the response piece we care about from the response
1265
- const myResult = result;
1266
- if (callProps.responseDatakey) {
1267
- myResult.response = jsonQuery(callProps.responseDatakey, { data: myResult.response }).value;
1268
- }
1269
-
1270
- // get the keys for the response fields
1271
- let rfKeys = [];
1272
- if (callProps.responseFields && Object.keys(callProps.responseFields).length > 0) {
1273
- rfKeys = Object.keys(callProps.responseFields);
1274
- }
1275
-
1276
- // if we got an array returned (e.g. getDevicesFitered)
1277
- if (Array.isArray(myResult.response)) {
1278
- const listDevices = [];
1279
- for (let a = 0; a < myResult.response.length; a += 1) {
1280
- const thisDevice = myResult.response[a];
1281
- for (let rf = 0; rf < rfKeys.length; rf += 1) {
1282
- if (rfKeys[rf] !== 'ostypePrefix') {
1283
- let fieldValue = getDataFromSources(callProps.responseFields[rfKeys[rf]], [thisDevice, devResp, callProps.requestFields]);
1284
-
1285
- // if the field is ostype - need to add prefix
1286
- if (rfKeys[rf] === 'ostype' && typeof fieldValue === 'string') {
1287
- fieldValue = ostypePrefix + fieldValue;
1288
- }
1289
- // if there is a status to set, set it
1290
- if (rfKeys[rf] === 'status') {
1291
- // if really looking for just a good response
1292
- if (callProps.responseFields[rfKeys[rf]] === 'return2xx' && myResult.icode === statusValue.toString()) {
1293
- thisDevice.isAlive = true;
1294
- } else if (fieldValue.toString() === statusValue.toString()) {
1295
- thisDevice.isAlive = true;
1296
- } else {
1297
- thisDevice.isAlive = false;
1298
- }
1299
- }
1300
- // if we found a good value
1301
- thisDevice[rfKeys[rf]] = fieldValue;
1302
- }
1303
- }
1304
-
1305
- // if there is no filter - add the device to the list
1306
- if (!filterName || filterName.length === 0) {
1307
- listDevices.push(thisDevice);
1308
- } else {
1309
- // if we have to match a filter
1310
- let found = false;
1311
- for (let f = 0; f < filterName.length; f += 1) {
1312
- if (thisDevice.name.indexOf(filterName[f]) >= 0) {
1313
- found = true;
1314
- break;
1315
- }
1316
- }
1317
- // matching device
1318
- if (found) {
1319
- listDevices.push(thisDevice);
1320
- }
1321
- }
1322
- }
1323
-
1324
- // return the array of devices
1325
- return callback(listDevices, null);
1326
- }
1327
-
1328
- // if this is not an array - just about everything else, just handle as a single object
1329
- let thisDevice = myResult.response;
1330
- for (let rf = 0; rf < rfKeys.length; rf += 1) {
1331
- // skip ostypePrefix since it is not a field
1332
- if (rfKeys[rf] !== 'ostypePrefix') {
1333
- let fieldValue = getDataFromSources(callProps.responseFields[rfKeys[rf]], [thisDevice, devResp, callProps.requestFields]);
1334
-
1335
- // if the field is ostype - need to add prefix
1336
- if (rfKeys[rf] === 'ostype' && typeof fieldValue === 'string') {
1337
- fieldValue = ostypePrefix + fieldValue;
1338
- }
1339
- // if there is a status to set, set it
1340
- if (rfKeys[rf] === 'status') {
1341
- // if really looking for just a good response
1342
- if (callProps.responseFields[rfKeys[rf]] === 'return2xx' && myResult.icode === statusValue.toString()) {
1343
- thisDevice.isAlive = true;
1344
- } else if (fieldValue.toString() === statusValue.toString()) {
1345
- thisDevice.isAlive = true;
1346
- } else {
1347
- thisDevice.isAlive = false;
1348
- }
1349
- }
1350
- // if we found a good value
1351
- thisDevice[rfKeys[rf]] = fieldValue;
1352
- }
1353
- }
1354
-
1355
- // if there is a filter - check the device is in the list
1356
- if (filterName && filterName.length > 0) {
1357
- let found = false;
1358
- for (let f = 0; f < filterName.length; f += 1) {
1359
- if (thisDevice.name.indexOf(filterName[f]) >= 0) {
1360
- found = true;
1361
- break;
1362
- }
1363
- }
1364
- // no matching device - clear the device
1365
- if (!found) {
1366
- thisDevice = {};
1367
- }
1368
- }
1369
-
1370
- return callback(thisDevice, null);
1371
- });
1372
- } catch (e) {
1373
- const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Caught Exception', null, null, null, e);
1374
- log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1375
- return callback(null, errorObj);
1376
- }
1061
+ return this.requestHandlerInst.getDevice(deviceName, callback);
1377
1062
  }
1378
1063
 
1379
1064
  /**
1380
1065
  * @summary Get Appliance that match the deviceName
1381
1066
  *
1382
- * @function getDevice
1067
+ * @function getDeviceAuth
1383
1068
  * @param {String} deviceName - the deviceName to find (required)
1069
+ * @param {Object} callOptions - Additional options used to make request, including auth headers, AWS service, or datatypes
1384
1070
  *
1385
1071
  * @param {getCallback} callback - a callback function to return the result
1386
1072
  * (appliance) or the error
1387
1073
  */
1388
- getDevice(deviceName, callback) {
1389
- const meth = 'adapterBase-getDevice';
1390
- const origin = `${this.id}-${meth}`;
1074
+ getDeviceAuth(deviceName, callOptions, callback) {
1075
+ const origin = `${this.id}-adapterBase-getDeviceAuth`;
1391
1076
  log.trace(origin);
1392
1077
 
1393
- // make sure we are set up for device broker getDevice
1394
- if (!this.allProps.devicebroker || !this.allProps.devicebroker.getDevice || this.allProps.devicebroker.getDevice.length === 0 || !this.allProps.devicebroker.getDevice[0].path) {
1395
- const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Missing Properties', ['devicebroker.getDevice.path'], null, null, null);
1396
- log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1397
- return callback(null, errorObj);
1398
- }
1399
-
1400
- /* HERE IS WHERE YOU VALIDATE DATA */
1401
- if (deviceName === undefined || deviceName === null || deviceName === '' || deviceName.length === 0) {
1402
- const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Missing Data', ['deviceName'], null, null, null);
1403
- log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1404
- return callback(null, errorObj);
1405
- }
1406
-
1407
- try {
1408
- // need to get the device so we can convert the deviceName to an id
1409
- // !! if we can do a lookup by name the getDevicesFiltered may not be necessary
1410
- const opts = {
1411
- filter: {
1412
- name: deviceName
1413
- }
1414
- };
1415
- return this.getDevicesFiltered(opts, (devs, ferr) => {
1416
- // if we received an error or their is no response on the results return an error
1417
- if (ferr) {
1418
- return callback(null, ferr);
1419
- }
1420
- if (devs.list.length < 1) {
1421
- const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, `Did Not Find Device ${deviceName}`, [], null, null, null);
1422
- log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1423
- return callback(null, errorObj);
1424
- }
1425
-
1426
- const callPromises = [];
1427
- for (let i = 0; i < this.allProps.devicebroker.getDevice.length; i += 1) {
1428
- // Perform component calls here.
1429
- callPromises.push(
1430
- new Promise((resolve, reject) => {
1431
- this.iapMakeBrokerCall('getDevice', this.allProps.devicebroker.getDevice[i], [devs.list[0]], null, (callRet, callErr) => {
1432
- // return an error
1433
- if (callErr) {
1434
- reject(callErr);
1435
- } else {
1436
- // return the data
1437
- resolve(callRet);
1438
- }
1439
- });
1440
- })
1441
- );
1442
- }
1443
-
1444
- // return an array of repsonses
1445
- return Promise.all(callPromises).then((results) => {
1446
- let myResult = {};
1447
- results.forEach((result) => {
1448
- myResult = { ...myResult, ...result };
1449
- });
1450
-
1451
- return callback(myResult, null);
1452
- });
1453
- });
1454
- } catch (ex) {
1455
- const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Caught Exception', null, null, null, ex);
1456
- log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1457
- return callback(null, errorObj);
1458
- }
1078
+ return this.requestHandlerInst.getDeviceAuth(deviceName, callOptions, callback);
1459
1079
  }
1460
1080
 
1461
1081
  /**
@@ -1468,89 +1088,27 @@ class AdapterBase extends EventEmitterCl {
1468
1088
  * (appliances) or the error
1469
1089
  */
1470
1090
  getDevicesFiltered(options, callback) {
1471
- const meth = 'adapterBase-getDevicesFiltered';
1472
- const origin = `${this.id}-${meth}`;
1091
+ const origin = `${this.id}-adapterBase-getDevicesFiltered`;
1473
1092
  log.trace(origin);
1474
1093
 
1475
- // make sure we are set up for device broker getDevicesFiltered
1476
- if (!this.allProps.devicebroker || !this.allProps.devicebroker.getDevicesFiltered || this.allProps.devicebroker.getDevicesFiltered.length === 0 || !this.allProps.devicebroker.getDevicesFiltered[0].path) {
1477
- const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Missing Properties', ['devicebroker.getDevicesFiltered.path'], null, null, null);
1478
- log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1479
- return callback(null, errorObj);
1480
- }
1481
-
1482
- // verify the required fields have been provided
1483
- if (options === undefined || options === null || options === '' || options.length === 0) {
1484
- const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Missing Data', ['options'], null, null, null);
1485
- log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1486
- return callback(null, errorObj);
1487
- }
1488
- log.debug(`Device Filter Options: ${JSON.stringify(options)}`);
1489
-
1490
- try {
1491
- // TODO - get pagination working
1492
- // const nextToken = options.start;
1493
- // const maxResults = options.limit;
1494
-
1495
- // set up the filter of Device Names
1496
- let filterName = [];
1497
- if (options && options.filter && options.filter.name) {
1498
- // when this hack is removed, remove the lint ignore above
1499
- if (Array.isArray(options.filter.name)) {
1500
- // eslint-disable-next-line prefer-destructuring
1501
- filterName = options.filter.name;
1502
- } else {
1503
- filterName = [options.filter.name];
1504
- }
1505
- }
1506
-
1507
- // TODO - get sort and order working
1508
- /*
1509
- if (options && options.sort) {
1510
- reqObj.uriOptions.sort = JSON.stringify(options.sort);
1511
- }
1512
- if (options && options.order) {
1513
- reqObj.uriOptions.order = options.order;
1514
- }
1515
- */
1516
- const callPromises = [];
1517
- for (let i = 0; i < this.allProps.devicebroker.getDevicesFiltered.length; i += 1) {
1518
- // Perform component calls here.
1519
- callPromises.push(
1520
- new Promise((resolve, reject) => {
1521
- this.iapMakeBrokerCall('getDevicesFiltered', this.allProps.devicebroker.getDevicesFiltered[i], [{ fake: 'fakedata' }], filterName, (callRet, callErr) => {
1522
- // return an error
1523
- if (callErr) {
1524
- reject(callErr);
1525
- } else {
1526
- // return the data
1527
- resolve(callRet);
1528
- }
1529
- });
1530
- })
1531
- );
1532
- }
1094
+ return this.requestHandlerInst.getDevicesFiltered(options, callback);
1095
+ }
1533
1096
 
1534
- // return an array of repsonses
1535
- return Promise.all(callPromises).then((results) => {
1536
- let myResult = [];
1537
- results.forEach((result) => {
1538
- if (Array.isArray(result)) {
1539
- myResult = [...myResult, ...result];
1540
- } else if (Object.keys(result).length > 0) {
1541
- myResult.push(result);
1542
- }
1543
- });
1097
+ /**
1098
+ * @summary Get Appliances that match the filter
1099
+ *
1100
+ * @function getDevicesFilteredAuth
1101
+ * @param {Object} options - the data to use to filter the appliances (optional)
1102
+ * @param {Object} callOptions - Additional options used to make request, including auth headers, AWS service, or datatypes
1103
+ *
1104
+ * @param {getCallback} callback - a callback function to return the result
1105
+ * (appliances) or the error
1106
+ */
1107
+ getDevicesFilteredAuth(options, callOptions, callback) {
1108
+ const origin = `${this.id}-adapterBase-getDevicesFilteredAuth`;
1109
+ log.trace(origin);
1544
1110
 
1545
- log.debug(`${origin}: Found #${myResult.length} devices.`);
1546
- log.debug(`Devices: ${JSON.stringify(myResult)}`);
1547
- return callback({ total: myResult.length, list: myResult });
1548
- });
1549
- } catch (ex) {
1550
- const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Caught Exception', null, null, null, ex);
1551
- log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1552
- return callback(null, errorObj);
1553
- }
1111
+ return this.requestHandlerInst.getDevicesFilteredAuth(options, callOptions, callback);
1554
1112
  }
1555
1113
 
1556
1114
  /**
@@ -1563,80 +1121,27 @@ class AdapterBase extends EventEmitterCl {
1563
1121
  * (appliance isAlive) or the error
1564
1122
  */
1565
1123
  isAlive(deviceName, callback) {
1566
- const meth = 'adapterBase-isAlive';
1567
- const origin = `${this.id}-${meth}`;
1124
+ const origin = `${this.id}-adapterBase-isAlive`;
1568
1125
  log.trace(origin);
1569
1126
 
1570
- // make sure we are set up for device broker isAlive
1571
- if (!this.allProps.devicebroker || !this.allProps.devicebroker.isAlive || this.allProps.devicebroker.isAlive.length === 0 || !this.allProps.devicebroker.isAlive[0].path) {
1572
- const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Missing Properties', ['devicebroker.isAlive.path'], null, null, null);
1573
- log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1574
- return callback(null, errorObj);
1575
- }
1576
-
1577
- // verify the required fields have been provided
1578
- if (deviceName === undefined || deviceName === null || deviceName === '' || deviceName.length === 0) {
1579
- const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Missing Data', ['deviceName'], null, null, null);
1580
- log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1581
- return callback(null, errorObj);
1582
- }
1583
-
1584
- try {
1585
- // need to get the device so we can convert the deviceName to an id
1586
- // !! if we can do a lookup by name the getDevicesFiltered may not be necessary
1587
- const opts = {
1588
- filter: {
1589
- name: deviceName
1590
- }
1591
- };
1592
- return this.getDevicesFiltered(opts, (devs, ferr) => {
1593
- // if we received an error or their is no response on the results return an error
1594
- if (ferr) {
1595
- return callback(null, ferr);
1596
- }
1597
- if (devs.list.length < 1) {
1598
- const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, `Did Not Find Device ${deviceName}`, [], null, null, null);
1599
- log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1600
- return callback(null, errorObj);
1601
- }
1602
-
1603
- const callPromises = [];
1604
- for (let i = 0; i < this.allProps.devicebroker.isAlive.length; i += 1) {
1605
- // Perform component calls here.
1606
- callPromises.push(
1607
- new Promise((resolve, reject) => {
1608
- this.iapMakeBrokerCall('isAlive', this.allProps.devicebroker.isAlive[i], [devs.list[0]], null, (callRet, callErr) => {
1609
- // return an error
1610
- if (callErr) {
1611
- reject(callErr);
1612
- } else {
1613
- // return the data
1614
- resolve(callRet);
1615
- }
1616
- });
1617
- })
1618
- );
1619
- }
1127
+ return this.requestHandlerInst.isAlive(deviceName, callback);
1128
+ }
1620
1129
 
1621
- // return an array of repsonses
1622
- return Promise.all(callPromises).then((results) => {
1623
- let myResult = {};
1624
- results.forEach((result) => {
1625
- myResult = { ...myResult, ...result };
1626
- });
1130
+ /**
1131
+ * @summary Gets the status for the provided appliance
1132
+ *
1133
+ * @function isAliveAuth
1134
+ * @param {String} deviceName - the deviceName of the appliance. (required)
1135
+ * @param {Object} callOptions - Additional options used to make request, including auth headers, AWS service, or datatypes
1136
+ *
1137
+ * @param {configCallback} callback - callback function to return the result
1138
+ * (appliance isAliveAuth) or the error
1139
+ */
1140
+ isAliveAuth(deviceName, callOptions, callback) {
1141
+ const origin = `${this.id}-adapterBase-isAliveAuth`;
1142
+ log.trace(origin);
1627
1143
 
1628
- let response = true;
1629
- if (myResult.isAlive !== null && myResult.isAlive !== undefined && myResult.isAlive === false) {
1630
- response = false;
1631
- }
1632
- return callback(response);
1633
- });
1634
- });
1635
- } catch (ex) {
1636
- const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Caught Exception', null, null, null, ex);
1637
- log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1638
- return callback(null, errorObj);
1639
- }
1144
+ return this.requestHandlerInst.isAliveAuth(deviceName, callOptions, callback);
1640
1145
  }
1641
1146
 
1642
1147
  /**
@@ -1650,80 +1155,28 @@ class AdapterBase extends EventEmitterCl {
1650
1155
  * (appliance config) or the error
1651
1156
  */
1652
1157
  getConfig(deviceName, format, callback) {
1653
- const meth = 'adapterBase-getConfig';
1654
- const origin = `${this.id}-${meth}`;
1158
+ const origin = `${this.id}-adapterBase-getConfig`;
1655
1159
  log.trace(origin);
1656
1160
 
1657
- // make sure we are set up for device broker getConfig
1658
- if (!this.allProps.devicebroker || !this.allProps.devicebroker.getConfig || this.allProps.devicebroker.getConfig.length === 0 || !this.allProps.devicebroker.getConfig[0].path) {
1659
- const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Missing Properties', ['devicebroker.getConfig.path'], null, null, null);
1660
- log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1661
- return callback(null, errorObj);
1662
- }
1663
-
1664
- // verify the required fields have been provided
1665
- if (deviceName === undefined || deviceName === null || deviceName === '' || deviceName.length === 0) {
1666
- const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Missing Data', ['deviceName'], null, null, null);
1667
- log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1668
- return callback(null, errorObj);
1669
- }
1670
-
1671
- try {
1672
- // need to get the device so we can convert the deviceName to an id
1673
- // !! if we can do a lookup by name the getDevicesFiltered may not be necessary
1674
- const opts = {
1675
- filter: {
1676
- name: deviceName
1677
- }
1678
- };
1679
- return this.getDevicesFiltered(opts, (devs, ferr) => {
1680
- // if we received an error or their is no response on the results return an error
1681
- if (ferr) {
1682
- return callback(null, ferr);
1683
- }
1684
- if (devs.list.length < 1) {
1685
- const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, `Did Not Find Device ${deviceName}`, [], null, null, null);
1686
- log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1687
- return callback(null, errorObj);
1688
- }
1161
+ return this.requestHandlerInst.getConfig(deviceName, format, callback);
1162
+ }
1689
1163
 
1690
- const callPromises = [];
1691
- for (let i = 0; i < this.allProps.devicebroker.getConfig.length; i += 1) {
1692
- // Perform component calls here.
1693
- callPromises.push(
1694
- new Promise((resolve, reject) => {
1695
- this.iapMakeBrokerCall('getConfig', this.allProps.devicebroker.getConfig[i], [devs.list[0]], null, (callRet, callErr) => {
1696
- // return an error
1697
- if (callErr) {
1698
- reject(callErr);
1699
- } else {
1700
- // return the data
1701
- resolve(callRet);
1702
- }
1703
- });
1704
- })
1705
- );
1706
- }
1164
+ /**
1165
+ * @summary Gets a config for the provided Appliance
1166
+ *
1167
+ * @function getConfigAuth
1168
+ * @param {String} deviceName - the deviceName of the appliance. (required)
1169
+ * @param {String} format - the desired format of the config. (optional)
1170
+ * @param {Object} callOptions - Additional options used to make request, including auth headers, AWS service, or datatypes
1171
+ *
1172
+ * @param {configCallback} callback - callback function to return the result
1173
+ * (appliance config) or the error
1174
+ */
1175
+ getConfigAuth(deviceName, format, callOptions, callback) {
1176
+ const origin = `${this.id}-adapterBase-getConfigAuth`;
1177
+ log.trace(origin);
1707
1178
 
1708
- // return an array of repsonses
1709
- return Promise.all(callPromises).then((results) => {
1710
- let myResult = {};
1711
- results.forEach((result) => {
1712
- myResult = { ...myResult, ...result };
1713
- });
1714
-
1715
- // return the result
1716
- const newResponse = {
1717
- response: JSON.stringify(myResult, null, 2)
1718
- };
1719
- return callback(newResponse, null);
1720
- });
1721
- });
1722
- } catch (ex) {
1723
- const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Caught Exception', null, null, null, ex);
1724
- log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1725
- return callback(null, errorObj);
1726
- }
1179
+ return this.requestHandlerInst.getConfigAuth(deviceName, format, callOptions, callback);
1727
1180
  }
1728
1181
 
1729
1182
  /**
@@ -1735,47 +1188,258 @@ class AdapterBase extends EventEmitterCl {
1735
1188
  * (count) or the error
1736
1189
  */
1737
1190
  iapGetDeviceCount(callback) {
1738
- const meth = 'adapterBase-iapGetDeviceCount';
1191
+ const origin = `${this.id}-adapterBase-iapGetDeviceCount`;
1192
+ log.trace(origin);
1193
+
1194
+ return this.requestHandlerInst.iapGetDeviceCount(callback);
1195
+ }
1196
+
1197
+ /**
1198
+ * @summary Gets the device count from the system
1199
+ *
1200
+ * @function iapGetDeviceCountAuth
1201
+ * @param {Object} callOptions - Additional options used to make request, including auth headers, AWS service, or datatypes
1202
+ *
1203
+ * @param {getCallback} callback - callback function to return the result
1204
+ * (count) or the error
1205
+ */
1206
+ iapGetDeviceCountAuth(callOptions, callback) {
1207
+ const origin = `${this.id}-adapterBase-iapGetDeviceCountAuth`;
1208
+ log.trace(origin);
1209
+
1210
+ return this.requestHandlerInst.iapGetDeviceCountAuth(callOptions, callback);
1211
+ }
1212
+
1213
+ /* ********************************************** */
1214
+ /* */
1215
+ /* EXPOSES GENERIC HANDLER */
1216
+ /* */
1217
+ /* ********************************************** */
1218
+ /**
1219
+ * Makes the requested generic call
1220
+ *
1221
+ * @function iapExpandedGenericAdapterRequest
1222
+ * @param {Object} metadata - metadata for the call (optional).
1223
+ * Can be a stringified Object.
1224
+ * @param {String} uriPath - the path of the api call - do not include the host, port, base path or version (optional)
1225
+ * @param {String} restMethod - the rest method (GET, POST, PUT, PATCH, DELETE) (optional)
1226
+ * @param {Object} pathVars - the parameters to be put within the url path (optional).
1227
+ * Can be a stringified Object.
1228
+ * @param {Object} queryData - the parameters to be put on the url (optional).
1229
+ * Can be a stringified Object.
1230
+ * @param {Object} requestBody - the body to add to the request (optional).
1231
+ * Can be a stringified Object.
1232
+ * @param {Object} addlHeaders - additional headers to be put on the call (optional).
1233
+ * Can be a stringified Object.
1234
+ * @param {getCallback} callback - a callback function to return the result (Generics)
1235
+ * or the error
1236
+ */
1237
+ iapExpandedGenericAdapterRequest(metadata, uriPath, restMethod, pathVars, queryData, requestBody, addlHeaders, callback) {
1238
+ const origin = `${this.myid}-adapterBase-iapExpandedGenericAdapterRequest`;
1239
+ log.trace(origin);
1240
+
1241
+ return this.requestHandlerInst.expandedGenericAdapterRequest(metadata, uriPath, restMethod, pathVars, queryData, requestBody, addlHeaders, callback);
1242
+ }
1243
+
1244
+ /**
1245
+ * Makes the requested generic call
1246
+ *
1247
+ * @function genericAdapterRequest
1248
+ * @param {String} uriPath - the path of the api call - do not include the host, port, base path or version (required)
1249
+ * @param {String} restMethod - the rest method (GET, POST, PUT, PATCH, DELETE) (required)
1250
+ * @param {Object} queryData - the parameters to be put on the url (optional).
1251
+ * Can be a stringified Object.
1252
+ * @param {Object} requestBody - the body to add to the request (optional).
1253
+ * Can be a stringified Object.
1254
+ * @param {Object} addlHeaders - additional headers to be put on the call (optional).
1255
+ * Can be a stringified Object.
1256
+ * @param {getCallback} callback - a callback function to return the result (Generics)
1257
+ * or the error
1258
+ */
1259
+ genericAdapterRequest(uriPath, restMethod, queryData, requestBody, addlHeaders, callback) {
1260
+ const origin = `${this.myid}-adapterBase-genericAdapterRequest`;
1261
+ log.trace(origin);
1262
+
1263
+ return this.requestHandlerInst.genericAdapterRequest(uriPath, restMethod, queryData, requestBody, addlHeaders, callback);
1264
+ }
1265
+
1266
+ /**
1267
+ * Makes the requested generic call with no base path or version
1268
+ *
1269
+ * @function genericAdapterRequestNoBasePath
1270
+ * @param {String} uriPath - the path of the api call - do not include the host, port, base path or version (required)
1271
+ * @param {String} restMethod - the rest method (GET, POST, PUT, PATCH, DELETE) (required)
1272
+ * @param {Object} queryData - the parameters to be put on the url (optional).
1273
+ * Can be a stringified Object.
1274
+ * @param {Object} requestBody - the body to add to the request (optional).
1275
+ * Can be a stringified Object.
1276
+ * @param {Object} addlHeaders - additional headers to be put on the call (optional).
1277
+ * Can be a stringified Object.
1278
+ * @param {getCallback} callback - a callback function to return the result (Generics)
1279
+ * or the error
1280
+ */
1281
+ genericAdapterRequestNoBasePath(uriPath, restMethod, queryData, requestBody, addlHeaders, callback) {
1282
+ const origin = `${this.myid}-adapterBase-genericAdapterRequestNoBasePath`;
1283
+ log.trace(origin);
1284
+
1285
+ return this.requestHandlerInst.genericAdapterRequestNoBasePath(uriPath, restMethod, queryData, requestBody, addlHeaders, callback);
1286
+ }
1287
+
1288
+ /* ********************************************** */
1289
+ /* */
1290
+ /* EXPOSES INVENTORY CALLS */
1291
+ /* */
1292
+ /* ********************************************** */
1293
+ /**
1294
+ * @summary run the adapter lint script to return the results.
1295
+ *
1296
+ * @function iapRunAdapterLint
1297
+ *
1298
+ * @return {Object} - containing the results of the lint call.
1299
+ */
1300
+ iapRunAdapterLint(callback) {
1301
+ const meth = 'adapterBase-iapRunAdapterLint';
1739
1302
  const origin = `${this.id}-${meth}`;
1740
1303
  log.trace(origin);
1304
+ let command = null;
1741
1305
 
1742
- // make sure we are set up for device broker getCount
1743
- if (!this.allProps.devicebroker || !this.allProps.devicebroker.getCount || this.allProps.devicebroker.getCount.length === 0 || !this.allProps.devicebroker.getCount[0].path) {
1744
- const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Missing Properties', ['devicebroker.getCount.path'], null, null, null);
1745
- log.error(`${origin}: ${errorObj.IAPerror.displayString}`);
1746
- return callback(null, errorObj);
1306
+ if (fs.existsSync('package.json')) {
1307
+ const packageData = require('./package.json');
1308
+
1309
+ // check if 'test', 'test:unit', 'test:integration' exists in package.json file
1310
+ if (!packageData.scripts || !packageData.scripts['lint:errors']) {
1311
+ log.error('The required script does not exist in the package.json file');
1312
+ return callback(null, 'The required script does not exist in the package.json file');
1313
+ }
1314
+
1315
+ // execute 'npm run lint:errors' command
1316
+ command = spawnSync('npm', ['run', 'lint:errors'], { cwd: __dirname, encoding: 'utf-8' });
1317
+
1318
+ // analyze and format the response
1319
+ const result = {
1320
+ status: 'SUCCESS'
1321
+ };
1322
+ if (command.status !== 0) {
1323
+ result.status = 'FAILED';
1324
+ result.output = command.stdout;
1325
+ }
1326
+ return callback(result);
1747
1327
  }
1748
1328
 
1749
- // verify the required fields have been provided
1329
+ log.error('Package Not Found');
1330
+ return callback(null, 'Package Not Found');
1331
+ }
1750
1332
 
1751
- try {
1752
- const callPromises = [];
1753
- for (let i = 0; i < this.allProps.devicebroker.getCount.length; i += 1) {
1754
- // Perform component calls here.
1755
- callPromises.push(
1756
- new Promise((resolve, reject) => {
1757
- this.iapMakeBrokerCall('getCount', this.allProps.devicebroker.getCount[i], null, null, (callRet, callErr) => {
1758
- // return an error
1759
- if (callErr) {
1760
- reject(callErr);
1761
- } else {
1762
- // return the data
1763
- resolve(callRet);
1764
- }
1765
- });
1766
- })
1767
- );
1333
+ /**
1334
+ * @summary run the adapter test scripts (baseunit and unit) to return the results.
1335
+ * can not run integration as there can be implications with that.
1336
+ *
1337
+ * @function iapRunAdapterTests
1338
+ *
1339
+ * @return {Object} - containing the results of the baseunit and unit tests.
1340
+ */
1341
+ iapRunAdapterTests(callback) {
1342
+ const meth = 'adapterBase-iapRunAdapterTests';
1343
+ const origin = `${this.id}-${meth}`;
1344
+ log.trace(origin);
1345
+ let basecommand = null;
1346
+ let command = null;
1347
+
1348
+ if (fs.existsSync('package.json')) {
1349
+ const packageData = require('./package.json');
1350
+
1351
+ // check if 'test', 'test:unit', 'test:integration' exists in package.json file
1352
+ if (!packageData.scripts || !packageData.scripts['test:baseunit'] || !packageData.scripts['test:unit']) {
1353
+ log.error('The required scripts do not exist in the package.json file');
1354
+ return callback(null, 'The required scripts do not exist in the package.json file');
1768
1355
  }
1769
1356
 
1770
- // return an array of repsonses
1771
- return Promise.all(callPromises).then((results) => {
1772
- let myResult = {};
1773
- results.forEach((result) => {
1774
- myResult = { ...myResult, ...result };
1775
- });
1357
+ // run baseunit test
1358
+ basecommand = spawnSync('npm', ['run', 'test:baseunit'], { cwd: __dirname, encoding: 'utf-8' });
1776
1359
 
1777
- // return the result
1778
- return callback({ count: myResult.length });
1360
+ // analyze and format the response to baseunit
1361
+ const baseresult = {
1362
+ status: 'SUCCESS'
1363
+ };
1364
+ if (basecommand.status !== 0) {
1365
+ baseresult.status = 'FAILED';
1366
+ baseresult.output = basecommand.stdout;
1367
+ }
1368
+
1369
+ // run unit test
1370
+ command = spawnSync('npm', ['run', 'test:unit'], { cwd: __dirname, encoding: 'utf-8' });
1371
+
1372
+ // analyze and format the response to unit
1373
+ const unitresult = {
1374
+ status: 'SUCCESS'
1375
+ };
1376
+ if (command.status !== 0) {
1377
+ unitresult.status = 'FAILED';
1378
+ unitresult.output = command.stdout;
1379
+ }
1380
+
1381
+ // format the response and return it
1382
+ const result = {
1383
+ base: baseresult,
1384
+ unit: unitresult
1385
+ };
1386
+ return callback(result);
1387
+ }
1388
+
1389
+ log.error('Package Not Found');
1390
+ return callback(null, 'Package Not Found');
1391
+ }
1392
+
1393
+ /**
1394
+ * @summary provide inventory information abbout the adapter
1395
+ *
1396
+ * @function iapGetAdapterInventory
1397
+ *
1398
+ * @return {Object} - containing the adapter inventory information
1399
+ */
1400
+ iapGetAdapterInventory(callback) {
1401
+ const meth = 'adapterBase-iapGetAdapterInventory';
1402
+ const origin = `${this.id}-${meth}`;
1403
+ log.trace(origin);
1404
+
1405
+ try {
1406
+ // call to the adapter utils to get inventory
1407
+ return this.requestHandlerInst.getAdapterInventory((res, error) => {
1408
+ const adapterInv = res;
1409
+
1410
+ // get all of the tasks
1411
+ const allTasks = this.getAllFunctions();
1412
+ adapterInv.totalTasks = allTasks.length;
1413
+
1414
+ // get all of the possible workflow tasks
1415
+ const myIgnore = [
1416
+ 'healthCheck',
1417
+ 'iapGetAdapterWorkflowFunctions',
1418
+ 'hasEntities'
1419
+ ];
1420
+ adapterInv.totalWorkflowTasks = this.iapGetAdapterWorkflowFunctions(myIgnore).length;
1421
+
1422
+ // TODO: CACHE
1423
+ // CONFIRM CACHE
1424
+ // GET CACHE ENTITIES
1425
+
1426
+ // get the Device Count
1427
+ return this.iapGetDeviceCount((devres, deverror) => {
1428
+ // if call failed assume not broker integrated
1429
+ if (deverror) {
1430
+ adapterInv.brokerDefined = false;
1431
+ adapterInv.deviceCount = -1;
1432
+ } else {
1433
+ // broker confirmed
1434
+ adapterInv.brokerDefined = true;
1435
+ adapterInv.deviceCount = 0;
1436
+ if (devres && devres.count) {
1437
+ adapterInv.deviceCount = devres.count;
1438
+ }
1439
+ }
1440
+
1441
+ return callback(adapterInv);
1442
+ });
1779
1443
  });
1780
1444
  } catch (ex) {
1781
1445
  const errorObj = this.requestHandlerInst.formatErrorObject(this.id, meth, 'Caught Exception', null, null, null, ex);