Updated Sparky to add ECOMP functionality Browse, Specialized Search, BYOQ, and the...
[aai/sparky-fe.git] / src / app / byoq / CustomDsl.jsx
1 /*
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017-2021 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *       http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20 import React, {Component} from 'react';
21 import PanelGroup from 'react-bootstrap/lib/PanelGroup';
22 import Panel from 'react-bootstrap/lib/Panel';
23 import Modal from 'react-bootstrap/lib/Modal';
24 import Grid from 'react-bootstrap/lib/Grid';
25 import Button from 'react-bootstrap/lib/Button';
26 import ModelGallery from 'app/model/modelSearch/components/ModelGallery.jsx';
27 import Autosuggest from 'react-autosuggest';
28 import DatePicker from 'react-datepicker';
29 import moment from "moment";
30 import DslHints from 'app/assets/configuration/dsl_hints.json';
31 import DslDetailedHelp from 'app/assets/configuration/dsl_detailedHelp.json';
32 import {ExportExcel} from 'utils/ExportExcel.js';
33 import commonApi from 'utils/CommonAPIService.js';
34 import {GlobalExtConstants} from 'utils/GlobalExtConstants.js';
35 import {GeneralCommonFunctions} from 'utils/GeneralCommonFunctions.js';
36 import Spinner from 'utils/SpinnerContainer.jsx';
37 import OutputToggle from 'generic-components/OutputToggle.jsx';
38 import Pagination from 'react-js-pagination';
39 import Col from 'react-bootstrap/lib/Col';
40 import Row from 'react-bootstrap/lib/Row';
41 import OverlayTrigger from 'react-bootstrap/lib/OverlayTrigger';
42 import Tooltip from 'react-bootstrap/lib/Tooltip';
43 import OutputVisualization, {Visualization} from 'generic-components/OutputVisualization.jsx';
44 import ModelCard from 'app/model/modelSearch/components/ModelCard.jsx';
45 import CustomDSLSaveLoad from 'app/byoq/CustomDSLSaveLoad.jsx';
46 import FormGroup from 'react-bootstrap/lib/FormGroup';
47 import FormControl from 'react-bootstrap/lib/FormControl';
48 import ControlLabel from 'react-bootstrap/lib/ControlLabel';
49 import InfoToggle from 'generic-components/InfoToggle.jsx';
50 import Alert from 'react-bootstrap/lib/Alert';
51 import Tabs from 'react-bootstrap/lib/Tabs';
52 import Tab from 'react-bootstrap/lib/Tab';
53 import BootstrapTable from 'react-bootstrap-table-next';
54 import filterFactory, {textFilter,customFilter} from 'react-bootstrap-table2-filter';
55 import FilterTypes from 'generic-components/filter/components/FilterTypes.jsx';
56 import DownloadRangeModel from 'generic-components/DownloadRangeModel.jsx';
57 import SelectFilter from 'generic-components/filter/components/SelectFilter.jsx';
58 import Toggle from 'react-toggle';
59 import "react-toggle/style.css";
60 import BootstrapSwitchButton from 'bootstrap-switch-button-react';
61
62 let PAGINATION_CONSTANT = GlobalExtConstants.PAGINATION_CONSTANT;
63 let EDGERULES = GlobalExtConstants.EDGERULES;
64 let OXM = GlobalExtConstants.OXM;
65 let INVLIST = GlobalExtConstants.INVLIST;
66 let generateExcels = ExportExcel.generateExcels;
67 let DOWNLOAD_ALL = GlobalExtConstants.DOWNLOAD_ALL;
68 let DOWNLOAD_TOOLTIP = GlobalExtConstants.DOWNLOAD_TOOLTIP;
69 let filterTypeList = GlobalExtConstants.FILTER_TYPES;
70 let TABULAR_FILTER_TYPE = GlobalExtConstants.TABULAR_FILTER_TYPE;
71 let ENVIRONMENT = GlobalExtConstants.ENVIRONMENT;
72 let EMAIL_EXT = GlobalExtConstants.EMAIL_EXT;
73 let APERTURE_SERVICE = JSON.parse(sessionStorage.getItem(ENVIRONMENT + 'APERTURE_SERVICE'));
74 let buildAttrList = ExportExcel.buildAttrList;
75
76 let dslHints = null;
77 let nodeTypes = [];
78 let properties = null;
79 let traverseRulesDsl = [];
80 let inputValue = '';
81 let testData = null;
82
83 var settings = {
84         'NODESERVER': INVLIST.NODESERVER,
85         'PROXY': INVLIST.PROXY,
86         'PREFIX': INVLIST.PREFIX,
87         'VERSION': INVLIST.VERSION,
88         'USESTUBS': INVLIST.useStubs,
89         'APERTURE': INVLIST.APERTURE,
90         'TABULAR': INVLIST.TABULAR,
91         'TABULARVERSION': INVLIST.TABULARVERSION
92 };
93 class AttributeFilter extends Component {
94   
95         constructor(props) {
96           super(props);           
97           this.filter = this.filter.bind(this);
98           this.getValue = this.getValue.bind(this);
99           this.props = props;
100           this.state = {
101                 filterText: '',
102                 isPageChange: this.props.isPageChange,
103                 columnValue : ''
104           };
105         }
106         getValue = () => {
107           return this.input.value;
108         }
109         setPlaceHolder = () => {
110           let filterText = '';
111           filterText = 'Enter ' + this.props.column.text;
112           return filterText;
113         }
114         filter = () => {
115           let txt=this.props.column.text;
116           let obj = {};
117           obj[txt] = this.getValue();
118           var columnFilter = this.props.columnFilter; 
119          for(var i=0;i<columnFilter.length;i++){
120                 if(columnFilter[i][txt] != undefined){
121                   columnFilter[i][txt] = this.getValue();
122                   this.props.handleOnFilter(columnFilter,this.getValue());
123                   this.props.onFilter(this.getValue());
124                 }
125           }
126         }
127         render() {
128           return (
129                 <div>
130                   
131                         <input
132                         key="input"
133                         ref={ node => this.input = node }
134                         type="text"
135                           placeholder={this.setPlaceHolder()}
136                           onChange={this.filter}
137                         />
138                   
139                 </div>
140           )
141         }
142   }
143   
144 class CustomDsl extends Component {
145         nodeResults = '';
146         typeOfCall = true;
147         downloadTooltip = DOWNLOAD_TOOLTIP;
148         downloadAllTooltip = 'Downloads First ' + DOWNLOAD_ALL + ' Results';
149         downloadRangeTooltip= 'Download Results By Custom Range Selection';
150         downloadBulkTooltip= 'Download Results Of All Loaded Queries';
151         historyStackString = '';
152         dslObject={};
153         dslObjectList=[];
154         nodeTypeArray=[];
155         nodeTypeArrayList=[];
156         edgesArray=[];
157         relationsArray=[];
158         tempDslQuery='';
159         tempDslQueryList=[];
160         templateError=[];
161         templateErrorList={};
162         baseState='';
163         propertiesDsl = [];
164         tableFilterAliasColumns={};
165         constructor(props) {
166                 console.log('CustomDsl:Constuctor props>>>>',props);
167                 super(props);
168                 APERTURE_SERVICE=JSON.parse(sessionStorage.getItem(ENVIRONMENT + 'APERTURE_SERVICE'));
169     console.log('APERTURE_SERVICE: ' + APERTURE_SERVICE);
170                         TABULAR_FILTER_TYPE=(APERTURE_SERVICE && JSON.parse(sessionStorage.getItem(ENVIRONMENT + 'ENABLE_ANALYSIS')))?'CONTAINS':'=';
171             this.saveLoadComponent = React.createRef();
172                 this.saveLoadComponentDsl = React.createRef();
173                 this.state = {
174                         nodeTypes: [],
175                         hintHtml: {},
176                         header: null,
177                         multipleNodes: '',
178                         isLoading: false,
179                         nodes: [],
180                         simpleQueries: [],
181                         traversalQueries: [],
182                         unionQueries: [],
183                         negationQueries: [],
184                         topologyQueries: [],
185                         limitQueries: [],
186       advancedQueries: [],
187                         showModal: false,
188                         query: '',
189                         value: '',
190                         valuePreviousState: '',
191                         suggestions: [],
192                         edgeRules: [],
193                         previousNodeTypeDsl: '',
194                         selected: [],
195                         nodeTypeDsl: '',
196                         model: null,
197                         showPagination: false,
198                         showResults: false,
199                         activePage: 1,
200                         aggregateActivePage: 1,
201                         totalResults: 0,
202                         errorResults: false,
203                         errorMessage: '',
204                         noResults: true,
205                         validInput: false,
206                         isInitialLoad: true,
207                         prevQuery : '',
208                         showHistoryModal:false,
209                         startDate: moment(),
210             res: null,
211             visualAddition: false,
212             nodeDisplay: '',
213             showNodeModal: false,
214             focusedNode: {},
215                 historyType: 'dsl',
216                 focusedNodeUri: 0,
217                         viewName: localStorage.getItem(GlobalExtConstants.ENVIRONMENT + '_' + sessionStorage.getItem(GlobalExtConstants.ENVIRONMENT + 'userId') + '_viewPreference')  || 'CardLayout',
218                         focusedNodeType: '',
219                         historyParams: '' , 
220                         showModelOptions:false,
221                         enableCalendar: true,
222                         resetColumnFilters: true,
223                         isPageNumberChange: false,
224                         loadedQueries: [],
225                         queryDescription: '',
226                         queryName: '',                  
227                         category:'',
228                         saveSuccessfulMsg: false,
229                         saveErrorMsg: false,
230                         enableSaveBusyFeedback: false,
231                         isAggregate: false,
232                         isAggregatePreviousState: false,
233                         isAggregateChecked: false,
234                         isCommunitySharedPreviousState: false,
235                         isCommunitySharedChecked: false,
236                         associatedNodesEnabled: false,
237                         associatedNodesEnabledPreviuosState: false,
238                         aggregatePaths: [],
239                         aggregatePathAttrs: [],
240                         aggregateParentGroup: [],
241                         aggregateObjects: [],
242                         tabularAggregateColumns: [],
243                         tabularAggregateData: [],
244                         aggregateAttrList: [],
245                         aggregateNodes: [],
246                         allAggregateNodes: [],
247                         allres: null,
248                         allAggregatePaths: [],
249                         allAggregatePathAttrs: [],
250                         allAggregateObjects: [],
251                         allAggregateParentGroup: [],
252                         allTabularAggregateColumns: [],
253                         allTabularAggregateData: [],
254                         allAggregateAttrList: [],
255                         reRender: false,
256                         columnFilter: [],
257                         filterTemplateEntries: [],
258                         filterTemplateHeader: [],
259                         filterTemplateError: false,
260                         filterTemplateEntriesList:[],
261                         filterTemplateHeaderList:[],
262                         filterTemplateErrorList:[],
263                         nodeTypeOfDslTemplateList:[],
264                         valueList:[],
265                         templateQueryList:[],
266             editModel: {},
267             showEditModal: false,
268             templateQuery: '',
269             isDSLFlow: props.viewName === 'BYOQ',
270                         isSavedQueryFlow: props.viewName === 'Saved Queries',
271                         filterTypeDisplay: {'default':'Filter Type'},
272                         filterTypeDisplayList: [],
273                         disableFilter: true,
274                         totalPages: 0,
275                         pageRange: 1,
276                         showDownloadResultsModal: false,
277                         errorDownloadResults:false,
278                         downloadErrorMsg: '',      
279                         enableModelBusyFeedback:false,
280                         downloadCount:DOWNLOAD_ALL,
281                         addAndTemplateState:false,
282                         nodeTypeOfDslTemplate:[],
283                         filterDisplay:'Select Property',
284                         queryId:'',
285                         queryNameList: [],
286                         queryDescriptionList: [],
287                         categoryList: [],
288                         isPublicCheckedList: [],
289                         isCommunitySharedList: [],
290                         queryIdList: [],
291                         isAggregateCheckedList:[],
292                         associatedNodesEnabledList: [],
293                         associatedNodesEnabledPreviuosStateList: [],
294                         enableTreeLoadBusyFeedback: false,
295             treeLoadErrMsg: null,
296                         isDataSteward: sessionStorage.getItem(ENVIRONMENT + 'roles') && sessionStorage.getItem(ENVIRONMENT + 'roles').indexOf('data_steward_ui_view') > -1,
297                         isPublicChecked: sessionStorage.getItem(ENVIRONMENT + 'roles') && sessionStorage.getItem(ENVIRONMENT + 'roles').indexOf('data_steward_ui_view') > -1,
298                         defaultViewName: localStorage.getItem(GlobalExtConstants.ENVIRONMENT + '_' + sessionStorage.getItem(GlobalExtConstants.ENVIRONMENT + 'userId') + '_viewPreference')  || 'CardLayout',
299                 isTypeahead: true,
300                         enableRealTime: JSON.parse(sessionStorage.getItem(ENVIRONMENT + 'ENABLE_ANALYSIS')),
301                         downloadTemplateStatus:false,
302                         failedDownloadedTemplate:[],
303                         failedDownloadedTemplateMsg:'',
304                         failedEmailTemplateMsg:'',
305                         isMergedTabsChecked:false,
306                         isGenerateEmailChecked: false,
307                         emailTriggerMsg:'',
308                         dslConfigArray: [],
309                         staticTemplateFilters: [],
310             staticTemplateFiltersList: [],
311             tableAggregateAliasColumns:{}
312                 }
313         }
314   componentWillMount = () => {
315     console.log('CustomDsl:componentWillMount',JSON.stringify(this.props));
316         if(!this.props.location.historyStackString){
317                 this.props.location.historyStackString = this.props.location.pathname + ',,Origin||';
318         }else{
319                 this.historyStackString = this.props.location.historyStackString;
320         }
321         dslHints = Object.values(DslHints);
322         this.setState( {hintHtml: dslHints});
323         this.processHelp( DslDetailedHelp );
324         console.log('how many nodes? ' + this.state.nodes.length);
325         this.processEdgeRules(EDGERULES);
326         nodeTypes = this.buildNodeList();               
327         this.setState({
328                 nodeTypes: nodeTypes},
329                 function () {
330                         console.log('nodeTypes: ' + this.state.nodeTypes.length) ;
331                         this.baseState=this.state;
332                         this.buildDynamicByoq('','','init');
333                 }
334         );      
335                 
336  }
337  buildDynamicByoq=(queryParam, makeCall, loadType)=> {
338     let query = '';
339     let shouldRun = makeCall;
340     if(queryParam){
341        query = queryParam;
342     }else if(this.props.match.params.type === 'built' || this.props.match.params.type === 'built-aggregate'){
343        query = atob(this.props.match.params.propId).replace('<pre>','').replace('</pre>','');
344        shouldRun = true;
345     }else{
346         shouldRun = true;
347                 let nodeType =  (this.props.match.params.type) ? this.props.match.params.type : '';
348                 let propIds = (this.props.match.params.propId) ? this.props.match.params.propId.split(';') : '';
349                 let propertyValue = '';
350                 for(var i  in propIds){
351                         let propValue = propIds[i].split(':');
352                         console.log(propValue[0] + '....' + propValue[1]);
353                         let atobPropValue = atob(propValue[1]).replace('<pre>','').replace('</pre>','');
354                         if(propertyValue == ''){
355                                 propertyValue ='(\'' + propValue[0] +'\',\''+ atobPropValue + '\')';
356                         }else{
357                                 propertyValue = propertyValue + '(\'' + propValue[0] +'\',\''+ atobPropValue + '\')';
358                         }                       
359                 }
360                 console.log('propertyValue>>>>>',propertyValue);
361             let relArray = (this.props.match.params.relArray) ? this.props.match.params.relArray.split('&') : '';
362             let relativeStr = '';
363             let str = '';
364             if(relArray.length>0){
365                 for(var n in relArray){
366                         relativeStr = relativeStr + relArray[n] + '*'
367                 }
368                 str = relativeStr.replace(/\*/g, '*,').slice(0, -1);
369             }
370             let relativeAttachStr = (str === '') ? '' : '>[' + str + ']';
371             //encPropValue = (nodeType === '') ? '': atob(propValue[1]);
372                 query = (nodeType === '') ? '' : nodeType + '*' + propertyValue + relativeAttachStr;
373                 if(loadType ==='init'){
374                         console.log('this.baseState>>>>>',this.baseState)
375                         this.baseState.value=query;
376                 }               
377         }
378         console.log('query>>>',query);
379         console.log('this.props.match.params.type>>>',this.props.match.params.type);
380         if(query != ''){
381                 this.nodeResults = '';
382                 this.typeOfCall = true;
383                 let isInitialLoad = this.state.isInitialLoad;
384                 this.setState( {value: query,validInput: true,isInitialLoad: false},() => { if(shouldRun){this.formQueryString(false, isInitialLoad,false)}});
385         } 
386 }
387   getNodeTypes = () =>{
388     var result = JSON.parse(OXM);
389     var arrayOfTypes = result['xml-bindings']['java-types'][0]['java-type'];
390     var nodeTypeArray = [];
391     for(var j = 0; j < arrayOfTypes.length; j++){
392         if(arrayOfTypes[j]['xml-root-element'] && arrayOfTypes[j]['xml-root-element'][0]
393             && arrayOfTypes[j]['xml-root-element'][0]['$'] && arrayOfTypes[j]['xml-root-element'][0]['$']['name']){
394             nodeTypeArray.push((arrayOfTypes[j]['xml-root-element'][0]['$']['name']).toLowerCase());
395         }
396     }
397     return nodeTypeArray;
398   }
399
400   getNodeTypeFromURI = (uri) => {
401     var nodeTypeArray = this.getNodeTypes();
402     var tokenizedUri = uri.split("/");
403     var nodeType = "";
404     var found = false;
405     for (var i = tokenizedUri.length - 1; i >= 0 && !found; i--){
406         if(nodeTypeArray.indexOf(tokenizedUri[i]) > -1){
407             nodeType = tokenizedUri[i];
408             found = true;
409         }
410     }
411     return nodeType;
412   }
413
414   getAttributesFromNodeType = (nt) => {
415     var result = JSON.parse(OXM);
416     var arrayOfTypes = result['xml-bindings']['java-types'][0]['java-type'];
417     var foundIndex = -1;
418     var attributesArray = [];
419     var nodeType = nt.replace(/-/g,'');
420         for (var i = 0; i < arrayOfTypes.length && foundIndex === -1; i++) {
421                 if(arrayOfTypes[i]['$'] && arrayOfTypes[i]['$']['name'] && arrayOfTypes[i]['$']['name'].toLowerCase() === nodeType){
422                     foundIndex = i;
423                 }
424         }
425     for (var j = 0; j < arrayOfTypes[foundIndex]['java-attributes'][0]['xml-element'].length; j++) {
426         let property =  arrayOfTypes[foundIndex]['java-attributes'][0]['xml-element'][j]['$']['name'];
427         let type = arrayOfTypes[foundIndex]['java-attributes'][0]['xml-element'][j]['$']['type'];
428         if (type === 'java.lang.String' || type === 'java.lang.Boolean') {
429             attributesArray.push(property);
430         }
431     }
432     return attributesArray;
433   }
434  
435   getAttributesFromPath = (path,tableAggregateAliasColumns) => {
436      var nodeParseArray = path.split('>');
437     console.log(nodeParseArray);
438     var attributeArray = [];
439     var aggregatePaths = this.state.aggregatePathAttrs;
440     if(!this.typeOfCall){
441         aggregatePaths = this.state.allAggregatePathAttrs;
442     }
443     for(var i = 0; i < nodeParseArray.length; i++){
444                 var nodeKey = nodeParseArray[i].trim(); 
445                 let tableColumnsBuilt = ExportExcel.buildAttrList(nodeKey,[],'required');
446         for(var j = 0; j <  aggregatePaths[nodeKey].length; j++){
447                         let desc=tableColumnsBuilt.map((a) => 
448                         {
449                                 if(a.value.toLowerCase()==aggregatePaths[nodeKey][j].toLowerCase())
450                                   return a.description;
451                                 else
452                                   return '';
453                         }).filter(function (el) {
454                                 return el != '';
455                         });
456                         if(desc.length===0){
457                                 desc.push('');
458                         }
459                         if(Object.keys(tableAggregateAliasColumns).length !== 0 && tableAggregateAliasColumns[nodeKey] && tableAggregateAliasColumns[nodeKey][0][aggregatePaths[nodeKey][j]]){
460                                 attributeArray.push(nodeKey + '|' + tableAggregateAliasColumns[nodeKey][0][aggregatePaths[nodeKey][j]] +'|'+ desc[0]);
461                         }else{
462                                 attributeArray.push(nodeKey + '|' + aggregatePaths[nodeKey][j] + '|' + desc[0]);
463                         }
464         }
465     }
466     return attributeArray;
467   }
468
469   buildNodeList = () => {
470                 var result = JSON.parse(OXM);
471                 var arrayOfTypes = result['xml-bindings']['java-types'][0]['java-type'];
472                 let nodeList = [];
473
474                 for (var i = 0; i < arrayOfTypes.length; i++) {
475                         var hasProperties = false;
476                         if (arrayOfTypes[i]['java-attributes']) {
477                             let elementLength = 0;
478                             if (arrayOfTypes[i]['java-attributes'][0]['xml-element']) {
479                                 elementLength = arrayOfTypes[i]['java-attributes'][0]['xml-element'].length;
480                             }
481                             for (var j = 0; j < elementLength; j++) {
482                                 let property = JSON.stringify(arrayOfTypes[i]['java-attributes'][0]['xml-element'][j]['xml-properties']);
483                                 if (property) { //add to the list
484                                 hasProperties = true;
485                                 }
486                             }
487                             if (hasProperties) {
488                                 let node = arrayOfTypes[i]['xml-root-element'][0]['$']['name'];
489                                 nodeList.push(node);
490                             }
491                         }
492                 }
493                 nodeList.sort();
494                 return nodeList;
495   }
496
497   processHelp(data) {
498                 //console.log('Data' + JSON.stringify(data));
499                 this.setState( {simpleQueries: data.simple } );
500                 console.log('Value' + JSON.stringify(this.state.simpleQueries));
501                 this.setState( {traversalQueries: data.traversal} );
502                 this.setState( {unionQueries: data.union} );
503                 this.setState( {negationQueries: data.negation} );
504                 this.setState( {topologyQueries: data.topology} );
505                 this.setState( {limitQueries: data.limit} );
506     this.setState( {advancedQueries: data.advanced} );
507   }
508
509   processEdgeRules = (data) => {
510                 var ruleArr = [];
511                 this.setState({
512                         edgeRules: data.rules
513                 });
514                 ruleArr = data.rules;
515                 // console.log("Rule"+JSON.stringify(ruleArr));
516                 // new = data.Rules;
517   }
518
519   hint = () => { // open modal
520     console.log('hint >> showModal');
521     this.setState({
522                   showModal:true
523     });
524     this.hints = this.state.html;
525   }
526
527   onAddItem = (event) => {
528           event.preventDefault();
529           GeneralCommonFunctions.scrollTo("outputBlock");
530       this.nodeResults = '';
531       this.typeOfCall = true;
532       this.setState({ viewName: this.state.defaultViewName, aggregateActivePage: 1, activePage: 1, nodes: [], aggregateNodes: [],errorResults:false},function () { this.formQueryString(false,false,false); }.bind(this));
533   };
534
535   formQueryString = (bypassCall, isInitialLoad, aggregateForGraph) =>{
536                 console.log('formQueryString>>>>>>this.state.value :',this.state.value);
537                 var DSLQuery = this.state.value;
538                 DSLQuery.trim();
539                 console.log('DSLQuery.trim().length: ' + DSLQuery.trim().length);
540                 let resp = '';
541                 if (DSLQuery.trim() !== '' || (this.props.match.params.type && DSLQuery.trim() !== '')){
542                         console.log('validInput.DSLQuery: ' + DSLQuery);
543                         this.setState({
544                             validInput: true,isInitialLoad: isInitialLoad
545                         });
546                         const payload = {dsl: DSLQuery};
547                         let format = 'simple';
548                         if((this.state.isAggregateChecked || (isInitialLoad && this.props.match.params.type === 'built-aggregate')) && !aggregateForGraph){
549                             format = 'aggregate';
550                             this.setState({isAggregateChecked: true});
551                         }
552                         let queryStr = '';
553                         if(this.typeOfCall){
554                             if(format === 'aggregate' || aggregateForGraph){
555                                 this.setState({isAggregate: true});
556                                 queryStr = 'dsl?format=' + format + '&resultIndex=' + this.state.aggregateActivePage + '&resultSize=' + PAGINATION_CONSTANT.RESULTS_PER_PAGE;
557                             }else{
558                                 this.setState({isAggregate: false});
559                                 queryStr = 'dsl?format=' + format + '&resultIndex='
560                                                         + this.state.activePage + '&resultSize=' + PAGINATION_CONSTANT.RESULTS_PER_PAGE;
561                             }
562                         }else{
563                                 let pagerange=this.state.pageRange.toString();
564                                 pagerange=pagerange.split('-');
565                                 if(pagerange.length > 1){
566                                         queryStr = 'dsl?format=' + format + '&resultIndex='+ parseInt(pagerange[0]) +'&resultSize=' + PAGINATION_CONSTANT.RESULTS_PER_PAGE + '&resultRangeEnd=' + parseInt(pagerange[1]);
567                                 }else{                                  
568                                         queryStr = 'dsl?format=' + format + '&resultIndex='+ 1 +'&resultSize=' + parseInt(pagerange);
569                                 } 
570                                 
571                         }
572                         const path = queryStr;
573                         this.state.header = DSLQuery;
574                         console.log('DSLQuery: ' + DSLQuery);
575                         console.log('payload: ' + JSON.stringify(payload));
576                         console.log('path: ' + path);
577                         if(aggregateForGraph){
578                              this.setState({isLoading: true, prevQuery:DSLQuery});
579                         } else if(this.typeOfCall){
580                                         if(this.state.prevQuery !== DSLQuery){
581                                     this.setState({isLoading: true,
582                                         totalResults: 0,
583                                         prevQuery:DSLQuery
584                                     });
585                                         }else{
586                                     this.setState({isLoading: true, nodes: [], aggregateNodes: [], prevQuery:DSLQuery});
587                                 }
588                         }
589                         if(!bypassCall){
590                                 resp = this.getNodes(settings, path, payload, aggregateForGraph);
591                         }
592                 }else { // write a msg
593                         console.log('validInput: ' + false);
594                         this.setState({
595                                 validInput: false,
596                                 isInitialLoad: isInitialLoad
597                         });
598                         GeneralCommonFunctions.scrollTo('dslInputError');
599                 }
600                 console.log('Response: ' + resp);
601   }
602
603   onSuggestionSelected = (event, { suggestion }) => {
604                 event.preventDefault();
605
606                 let item = suggestion;
607                 console.log('onSuggestionSelected.item: ' + item);
608                 console.log('onSuggestionSelected.inputValue: ' + inputValue);
609
610                 this.setState({
611                         selected: [...this.state.selected, item],
612                                 value: inputValue + item
613                         },
614                         function () {
615                         console.log('onSuggestionSelected.selected: ' + this.state.selected);
616                         console.log('onSuggestionSelected.value: ' + this.state.value);
617                 });
618                 //if (!item.includes('(')) {
619           if (item.indexOf('(') === -1) { // not found
620                         this.setState({previousNodeTypeDsl: item},
621                                 function () {
622                                         this.setState({
623                                         nodeTypeDsl: item
624                                         });
625                                         console.log('onSuggestionSelected.previousNodeTypeDsl: ' + this.state.previousNodeTypeDsl);
626                                         console.log('onSuggestionSelected.nodeTypeDsl: ' + this.state.nodeTypeDsl);
627                                 }
628                         );
629                 }
630   }
631
632   storeInputReference = autosuggest => {
633                 if (autosuggest !== null) {
634                         this.input = autosuggest.input;
635                 }
636   };
637
638   clear = () => {
639                 this.setState({
640                         value: '',
641                         previousNodeTypeDsl: '',
642             header: ''
643                 });
644   }
645
646   openSaveModal = () =>{
647         this.setState({
648                 showSaveModal: true,
649                 saveSuccessfulMsg: false,
650                 treeLoadErrMsg: false,
651                 isPublicChecked:this.state.isDataSteward,
652                 isCommunitySharedChecked: false,
653             isEditModal:false,
654             enableTreeLoadBusyFeedback: true,
655             dslConfigurableFiltersArray: []
656         });
657         this.getTreeFromDSL(this.state.value).then(tree => {
658              this.setState({enableTreeLoadBusyFeedback: false, dslConfigArray: this.getConfigArrayFromDSLTree(tree, [], [])});
659         });
660   };
661
662   handleTypeaheadChange = (event) =>{
663     this.setState({isTypeahead: event.target.checked});
664   }
665
666   closeSaveModal = () =>{
667         //Set previous loaded state
668           if(this.state.isEditModal){
669                   this.setState({
670                           value: this.state.valuePreviousState,
671                           isAggregateChecked: this.state.isAggregateCheckedPreviousState,
672                           isCommunitySharedChecked: this.state.isCommunitySharedCheckedPreviousState,
673                           associatedNodesEnabled: this.state.associatedNodesEnabledPreviousState,
674                           enableTreeLoadBusyFeedback: false
675                   });
676           }
677
678           this.setState({
679                   showSaveModal: false,
680                   queryDescription: '',
681                   queryName: '',                  
682                   category:'',
683                   enableSaveBusyFeedback: false,
684                   showQueryExistsWarning: false,
685                   saveFailureMsg: false,
686                   isEditModal:false
687           });
688   };
689
690   submitSave = (bypassDupeCheck) =>{
691         let existQueryName=false;
692         let queryId='';
693         Object.keys(this.state.loadedQueries).map((key) =>{
694                 if(this.state.loadedQueries[key].name === this.state.queryName){
695                         existQueryName=true;
696                         if(this.state.showQueryExistsWarning){
697                                 queryId=key;
698                         }                       
699                 }
700         });
701     if(!bypassDupeCheck && existQueryName){
702         this.setState({showQueryExistsWarning:true});
703     }else{
704         var aggregateString = "false";
705         if(this.state.isAggregateChecked){
706             aggregateString = "true";
707                 }
708                 var queryParam=(this.state.queryId==='')?queryId:this.state.queryId;
709         var body =  {
710                       "cols": [
711                           {
712                               "name": "query_name",
713                               "value": this.state.queryName
714                           },
715                           {
716                               "name": "creator",
717                               "value": sessionStorage.getItem(ENVIRONMENT + 'userId')
718                           },
719                           {
720                               "name": "description",
721                               "value": this.state.queryDescription
722                           },
723                           {
724                               "name": "is_aggregate",
725                               "value": aggregateString
726                           },
727                           {
728                               "name": "community_shared",
729                               "value": "" + this.state.isCommunitySharedChecked
730                           },
731                           {
732                               "name": "is_public",
733                               "value": "" + this.state.isPublicChecked
734                           },
735                           {
736                               "name": "template_details",
737                               "value": JSON.stringify(this.state.staticTemplateFilters)
738                           },
739                           {
740                               "name": "dsl",
741                               "value": btoa('<pre>' + this.state.value + '</pre>')
742                                                   }                                               
743                       ]
744                 }
745                 if(this.state.category && this.state.category !=''){
746                         let catObj={"name": "category","value": this.state.category}
747                         body['cols'].push(catObj);
748                 }
749                 let localVersion='';
750                 if(this.state.showQueryExistsWarning){
751                         if(bypassDupeCheck && this.state.loadedQueries[queryParam] && this.state.loadedQueries[queryParam].version ){
752                                 localVersion = this.state.loadedQueries[queryParam].version;;
753                                 body.version = localVersion;
754
755                         }
756                 }else{
757                         if(bypassDupeCheck && this.state.loadedQueries[this.state.queryId] && this.state.loadedQueries[this.state.queryId].version ){
758                                 localVersion = this.state.loadedQueries[this.state.queryId].version;;
759                                 body.version = localVersion;
760                         }
761                 }
762         
763                 this.setState({showQueryExistsWarning:false, enableSaveBusyFeedback:true});
764                 settings['ISTABULAR'] = true;
765                 let localQuery='queries';
766                 let localHeader=null; 
767                 if(queryParam !==''){
768                         localQuery += '/'+encodeURIComponent(queryParam);
769                         localHeader= [{
770                                 "name":"If-Match",
771                                 "value": localVersion
772                          }];
773                 }
774                 commonApi(settings, localQuery, 'PUT', body, 'BYOQSaveInfo', GlobalExtConstants.OVERRIDE_DOMAIN,null,localHeader)
775                         .then(res => {
776                                 console.log('res:' + res.data);
777                                 if(res.status === 201){
778                                     if(res.data.status && (res.data.status !== 200 && res.data.status !== 201)){
779                                         this.triggerSaveError(res.data);
780                                     }else{
781                                                                 if(this.state.isEditModal && this.state.isDSLFlow){
782                                                                         this.setState({
783                                                                                 value: this.state.valuePreviousState,
784                                                                                 isAggregateChecked: this.state.isAggregateCheckedPreviousState,
785                                                                                 isCommunitySharedChecked: this.state.isCommunitySharedCheckedPreviousState,
786                                                                                 associatedNodesEnabled: this.state.associatedNodesEnabledPreviousState,
787                                                                         });
788                                                                 }
789
790                                                                 let jumpToId = "saveSuccess";
791                                                                 if (this.state.isSavedQueryFlow && this.state.isEditModal){
792                                                                         jumpToId = "saveSuccessEdit";
793                                                                 }
794                                                                 else if(this.state.isSavedQueryFlow && !this.state.isEditModal){
795                                                                         jumpToId = "saveSuccessTemplate";
796                                                                 }
797
798                                                                 this.setState({
799                                                                         saveSuccessfulMsg: "The following query was successfully saved: " + this.state.queryName,
800                                                                         showSaveModal: false,
801                                                                         enableSaveBusyFeedback:false,
802                                                                 });
803
804                                                                 GeneralCommonFunctions.scrollTo(jumpToId);
805                                                                 if(this.state.isSavedQueryFlow){
806                                                                         this.saveLoadComponent.current.getQueries();
807                                                                 }else {
808                                                                         this.saveLoadComponentDsl.current.getQueries();
809                                                                 }
810                                }
811                            }else{
812                              this.triggerSaveError(res.data);
813                            }
814                         }, error=>{
815                             this.triggerSaveError(error.response.data);
816                         }).catch(error => {
817                             this.triggerSaveError(error);
818         });
819     }
820   };
821
822   triggerSaveError = (error) => {
823       console.error('[CustomDsl.jsx] error : ', JSON.stringify(error));
824         let errMsg = '';
825         if(error.status && error.message){
826             errMsg += "Error Occurred: " + error.status + ' - ' +error.message;
827         }else{
828             errMsg += "Error Occurred: " + JSON.stringify(error);
829         }
830         console.log(errMsg);
831         this.setState({saveFailureMsg: errMsg + " - Failed to save query : " + this.state.queryName, enableSaveBusyFeedback:false});
832         GeneralCommonFunctions.scrollTo("saveFailure");
833     }
834
835   handleQueryDescriptionChange =  (e) => {
836      this.setState({queryDescription: e.target.value});
837   };
838   handleQueryNameChange = (e) => {
839      this.setState({queryName: e.target.value});
840   };
841   handleQueryChange = (e) => {
842         this.setState({value: e.target.value});
843   };
844   handleCategoryChange = (e) =>{
845         this.setState({category: e.target.value});
846   };
847
848   setQueriesState = (savedQueries) =>{
849     this.setState({
850         loadedQueries: savedQueries
851     });
852   };
853
854   getNodes(settings, path, payload, graphCall) {
855                 this.setState({isLoading: true});
856                 settings['ISTABULAR'] = false;
857                 if(this.state.enableRealTime && APERTURE_SERVICE){
858                         settings['ISAPERTURE'] = this.state.enableRealTime;
859                 }else{
860                         Object.keys(settings).forEach((key)=>{
861                                 if(key==='ISAPERTURE'){
862                                         delete settings[key];
863                                 }
864                         })
865                 }
866                 console.dir('CustomDSL:settings:' + JSON.stringify(settings));
867                 console.log('CustomDSL:path:' + path);
868                 console.dir('CustomDSL:payload:' + JSON.stringify(payload));
869                 commonApi(settings, path, 'PUT', payload, 'BYOQDefault', null, null, [{
870                                                                                 "name":"X-DslApiVersion",
871                                                                                 "value": "V2"
872                                                                               }])
873                 .then(res => {
874                         console.log('CustomDSL: Response',Object.keys(res.data));
875                                 if(!graphCall && this.typeOfCall){
876                                         this.setState({aggregatePaths: [],
877                                                                 aggregateParentGroup: [],
878                                                                 aggregateObjects: []});
879                                 }
880                                 if(this.state.isAggregate){
881                                         if(graphCall){
882                                                 if(res.data.results.length > 0 && this.state.visualAddition){
883                                                         Visualization.chart('currentStateAggregate', [], [], res.data, this);
884                                                         this.setState({isLoading: false, nodes: res.data.results, res: res});
885                                                 }
886                                         }else{
887                                                 this.processAggregateData(res);
888                                         }
889                                 }else{
890                                         this.processData(res);
891                                         if(this.state.nodes.length > 0 && this.state.visualAddition){
892                                                 Visualization.chart('currentState', [], [], this.state.res.data, this);
893                                         }
894                                 }
895                         }, error=>{
896                                 if(this.typeOfCall){
897                                         this.triggerError(error);
898                                 }else{
899                                         let errMsg = this.renderErrorMsg(error);
900                                         this.setState({ isLoading: false,errorDownloadResults:true,downloadErrorMsg:errMsg,enableModelBusyFeedback:false});       
901                                 }                               
902                         }).catch(error => {
903                                 if(this.typeOfCall){
904                                         this.triggerError(error);
905                                 }else{
906                                         let errMsg = this.renderErrorMsg(error);
907                                         this.setState({ isLoading: false,errorDownloadResults:true,downloadErrorMsg:errMsg,enableModelBusyFeedback:false});       
908                         }
909           });
910                 //this.input.focus();
911   }
912
913   triggerError = (error) => {
914     console.error('[CustomDsl.jsx] triggerError error : ', JSON.stringify(error));
915         //this.processData('');
916         this.setState({isLoading: false,
917                 totalResults: 0,
918                 showPagination: false,
919                 showResults: false,
920                 isInitialLoad: false,
921                 noResults: true,
922                 errorResults: true                        
923           });
924         this.downloadAllTooltip = 'Downloads First ' + DOWNLOAD_ALL + ' Results';
925         let errMsg = this.renderErrorMsg(error);
926         this.setState({errorMessage:errMsg});
927         console.log(error.config);
928         this.input.focus();
929   }
930   renderErrorMsg = (error) =>{
931         let errMsg='';
932         if (error.response) {
933                 // The request was made and the server responded with a status code
934                 // that falls out of the range of 2xx
935                 console.log('[CustomDsl.jsx] error :', error.response);
936                 if(error.response.status){
937                     errMsg += " Code: " + error.response.status;
938                 }
939                 if(error.response.data){
940             errMsg += " - " + JSON.stringify(error.response.data);
941         }
942         } else if (error.request) {
943                 // The request was made but no response was received
944                 // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
945                 // http.ClientRequest in node.js
946                 console.log(error.request);
947                 errMsg += " - Request was made but no response received";
948         } else {
949                 // Something happened in setting up the request that triggered an Error
950                 console.log('Error', error.message);
951                 errMsg += " - Unknown error occurred " + error.message;
952         }
953    return errMsg;
954   }
955   formAliasFilterPropertes = ()  =>{
956         let tableAggregateAliasColumns={};
957         this.tableFilterAliasColumns={};
958         let dslQuery = this.state.value;
959         var limitPattern = /limit[\s]\d+|limit\d+/ig
960         var limitkey = dslQuery.match(limitPattern);
961         if(limitkey){
962                 dslQuery = dslQuery.replace(limitkey[limitkey.length-1],'').trim();
963         }
964         dslQuery = this.alterDslQueryByRemoveSpaces(dslQuery);
965         //New adding
966         this.dslObject={};
967         this.nodeTypeArray=[];
968         //create placeholders for NodeTypes with Propand Propvalues
969         this.tempDslQuery=this.formTempDslQuery(dslQuery);
970         //Preparing Json Object to render into Placeholder              
971         this.contructDslNodes(dslQuery,'node',false,false,false,false);
972         ;
973         let aliasRegex=/\'(\s)as(\s)\'|\'as\'/ig;
974         Object.keys(this.dslObject).map((nodekey)=>{
975                 let nodeprops=this.dslObject[nodekey][0]['props'];
976                 if(nodeprops){
977                         let nodeTypeProp = nodeprops[0].slice(1,-1).split(',');
978                         let objAlias = {};
979                         let filterObjAlias={};
980                         for(var s=0;s<nodeTypeProp.length;s++){
981                                 let nodeTypePropes=nodeTypeProp[s].match(aliasRegex);
982                                 let alias='';
983                                 let nprop='';
984                                 if(nodeTypePropes){
985                                         let nodeTypeSplit=nodeTypeProp[s].split(aliasRegex);
986                                         nprop=nodeTypeSplit[0].replace(/\'/g,'');                  
987                                         alias=nodeTypeSplit[nodeTypeSplit.length-1].replace(/\'/g,'');
988                                         objAlias[nprop]=alias;
989                                         filterObjAlias[alias]=nprop;
990                                 }
991                         }
992                         let nodeNo=parseInt(nodekey.substr(nodekey.length-2,nodekey.length-1).replace(/\-/g,''));
993                         let keyact=isNaN(nodeNo);
994                         let actKey=nodekey.split('-');
995                         if(!keyact){
996                                 actKey.splice(actKey.length-1,1);
997                                 nodekey=actKey.join('-')+nodeNo;
998                         }               
999                         if(!tableAggregateAliasColumns[nodekey]){   
1000                                 tableAggregateAliasColumns[nodekey]=[]; 
1001                                 tableAggregateAliasColumns[nodekey].push(objAlias);      
1002                         
1003                         } 
1004                         if(!this.tableFilterAliasColumns[nodekey]){   
1005                                 this.tableFilterAliasColumns[nodekey]=[]; 
1006                                 this.tableFilterAliasColumns[nodekey].push(filterObjAlias);               
1007                         }
1008                 }               
1009         });
1010         return tableAggregateAliasColumns;
1011   }
1012   processAggregateData = (resp) =>{
1013         console.log('CustomDSL:processAggregateData Response data: ' + JSON.stringify(resp.data));
1014         var downloadCount = DOWNLOAD_ALL;
1015         var uniqueNodePaths = [];
1016         var uniqueNodeAttributes = [];
1017         var groupingByStart = [];
1018                 var aggregateObjectArray = [];
1019                 if (resp.data && resp.data.results) {
1020                         for(var i = 0; i < resp.data.results.length; i++){
1021                                 var fullPath = "";
1022                                 var nodePath = "";
1023                                 var nodeTypesForPath = [];
1024                                 var startNodeKey = "";
1025                                 var aggregateObject = {};
1026                                 //Make sure everything is in an array, so pushing single element into the array
1027                                 if(!Array.isArray(resp.data.results[i])){
1028                                         var tempObj = Object.assign({}, resp.data.results[i]);
1029                                         resp.data.results[i] = [];
1030                                         resp.data.results[i].push(tempObj);
1031                                 }
1032                                 for(var j = 0; j < resp.data.results[i].length; j++){
1033                                         var objectIndex = 0;
1034                                         for(var key in resp.data.results[i][j]){
1035                                                 var nodeType = this.getNodeTypeFromURI(key);
1036                                                 if (objectIndex === 0){
1037                                                         startNodeKey = key;
1038                                                 }
1039                                                 objectIndex++;
1040                                                 var nodeTypeLabel = '';
1041                                                 if(nodeTypesForPath[nodeType] >= 1){
1042                                                         nodeTypeLabel = nodeType + nodeTypesForPath[nodeType];
1043                                                         nodeTypesForPath[nodeType] = nodeTypesForPath[nodeType]++;
1044                                                 }else if (nodeTypesForPath[nodeType] === 0){
1045                                                         nodeTypeLabel = nodeType + 1;
1046                                                         nodeTypesForPath[nodeType] = 1;
1047                                                 }else{
1048                                                         nodeTypeLabel = nodeType;
1049                                                         nodeTypesForPath[nodeType] = 0;
1050                                                 }
1051                                                 if(!uniqueNodeAttributes[nodeTypeLabel]){
1052                                                     uniqueNodeAttributes[nodeTypeLabel] = [];
1053                                                 }
1054                                                 for(var propKey in resp.data.results[i][j][key].properties){
1055                                                     if(uniqueNodeAttributes[nodeTypeLabel].indexOf(propKey) === -1){
1056                                                         uniqueNodeAttributes[nodeTypeLabel].push(propKey);
1057                                                     }
1058                                                         Object.defineProperty(resp.data.results[i][j][key].properties, nodeTypeLabel + '|' + propKey, Object.getOwnPropertyDescriptor(resp.data.results[i][j][key].properties, propKey));
1059                                                         delete resp.data.results[i][j][key].properties[propKey];
1060                                                 }
1061                                                 fullPath += key + ' > ';
1062                                                 nodePath += nodeTypeLabel + ' > ';
1063                                         }
1064                                         aggregateObject = Object.assign({}, aggregateObject, resp.data.results[i][j][startNodeKey].properties);
1065                                 }
1066                                 nodePath =  nodePath.substring(0, nodePath.length - 3);
1067                                 if(!aggregateObjectArray[nodePath]){
1068                                         aggregateObjectArray[nodePath] = [];
1069                                 }
1070                                 aggregateObjectArray[nodePath].push(aggregateObject);
1071                                 resp.data.results[i].fullPath = fullPath.substring(0, fullPath.length - 3);
1072                                 resp.data.results[i].nodePath = nodePath;
1073                                 if(!groupingByStart[startNodeKey]){
1074                                         groupingByStart[startNodeKey] = [];
1075                                         groupingByStart[startNodeKey].push(resp.data.results[i]);
1076                                 }else{
1077                                         groupingByStart[startNodeKey].push(resp.data.results[i]);
1078                                 }
1079                                 if(uniqueNodePaths.indexOf(resp.data.results[i].nodePath) === -1){
1080                                         uniqueNodePaths.push(resp.data.results[i].nodePath);
1081                                 }
1082                                 console.log('Grouping by Start: ' + JSON.stringify(groupingByStart));
1083                                 console.log('Unique Paths: ' + JSON.stringify(uniqueNodePaths));
1084                         }
1085                         if(this.typeOfCall){
1086                                 let totalResults = (resp.headers) ? parseInt(resp.headers['total-results']) : 0;
1087                                 console.log('totalResults>>>>>>>>>>>>>>>>>>>>>',totalResults);                          
1088                                 if(totalResults > DOWNLOAD_ALL){
1089                                         this.downloadAllTooltip = DOWNLOAD_ALL + ' results out of '+ totalResults +' results will be downloaded, Please filter results further to obtain full report';
1090                                 }else{
1091                                         this.downloadAllTooltip = (totalResults === 1) ?'Downloads ' + totalResults + ' Results' : 'Downloads all ' + totalResults + ' Results' ;
1092                                         downloadCount= totalResults;
1093                                 }       
1094                                 this.setState({
1095                                         aggregateNodes: resp.data.results,
1096                                         res: resp,
1097                                         aggregatePaths: uniqueNodePaths,
1098                                         aggregatePathAttrs: uniqueNodeAttributes,
1099                                         aggregateObjects: aggregateObjectArray,
1100                                         aggregateParentGroup: groupingByStart,
1101                                         isLoading: false,
1102                                         totalResults: totalResults,
1103                                         showResults: totalResults > 0 ? true : false,
1104                                         showPagination: totalResults > 0 ? true : false,
1105                                         isInitialLoad: false,
1106                                         noResults: totalResults > 0 ? false : true,
1107                                         errorResults: false,
1108                                         downloadCount: downloadCount,
1109                                 },function(){this.formatAggregateIntoTabular();});
1110                                 this.multipleNodes = this.state.aggregateNodes.length > 1;
1111                                 //this.setState({ viewName: "CardLayout" }); commented not to defaulting to CardView 
1112                         }else{
1113                                 console.log('else condition>>>>');                      
1114                                 if(resp.data && resp.data.results) {                    
1115                                         this.nodeResults = resp.data.results;
1116                                         let totalResults = 0;
1117                                         let totalPages = 0;
1118                                         totalResults = parseInt(resp.headers['total-results']);
1119                                         totalPages = parseInt(resp.headers['total-pages']);
1120                                         this.setState({
1121                                                 allAggregateNodes: resp.data.results,
1122                                                 allres: resp,
1123                                                 allAggregatePathAttrs: uniqueNodeAttributes,
1124                                                 allAggregatePaths: uniqueNodePaths,
1125                                                 allAggregateObjects: aggregateObjectArray,
1126                                                 allAggregateParentGroup: groupingByStart,
1127                                                 totalPages:totalPages,
1128                                                 totalResults:totalResults,
1129                                                 errorDownloadResults:false,
1130                                                 downloadErrorMsg:''                             
1131                                         },function(){this.formatAggregateIntoTabular();});
1132                                 }else{
1133                                         this.downloadAllTooltip = 'Downloads First ' + DOWNLOAD_ALL + ' Results';
1134                                 }
1135                                 this.setState({isLoading: false});
1136                         }
1137                 }
1138                 GeneralCommonFunctions.scrollTo("outputBlock");
1139   }
1140
1141   formatAggregateIntoTabular = () =>{
1142     let tableColumnsList = [];
1143     let tableDataList = [];
1144         let columnFilter = [];
1145         var aggregatePaths = [];
1146         var aggregateObjects = [];
1147         let tableAggregateAliasColumns=this.formAliasFilterPropertes();
1148         
1149         if(this.typeOfCall){
1150             aggregatePaths = this.state.aggregatePaths;
1151             aggregateObjects = this.state.aggregateObjects;
1152         }else{
1153             aggregatePaths = this.state.allAggregatePaths;
1154             aggregateObjects = this.state.allAggregateObjects;
1155         }
1156         for(var p = 0; p < aggregatePaths.length; p++){
1157                 var types = [aggregatePaths[p]];
1158                 var type = types[0];
1159                 var attributeList = this.getAttributesFromPath(type,tableAggregateAliasColumns);
1160                 var downloadAllCalled = false;
1161                 tableColumnsList[type] = [];
1162                 tableColumnsList[type].push({dataField: 'id', text: 'id', hidden: true });
1163                 tableDataList[type] = aggregateObjects[type];
1164                 for(var attrIndex = 0; attrIndex < attributeList.length; attrIndex++){
1165                         let col=attributeList[attrIndex].split('|').splice(0,2).join('|');
1166                         let desc=attributeList[attrIndex].split('|')[2];
1167                         if(!columnFilter[attrIndex] || (columnFilter[attrIndex] && columnFilter[attrIndex][attributeList[attrIndex]] === undefined)){
1168                                 let obj = {};                           
1169                                 obj[col] = '';
1170                                 obj['description']=desc
1171                                 columnFilter.push(obj);
1172                         }
1173                           if(!this.typeOfCall){
1174                                 tableColumnsList[type].push({name: col,
1175                                         dataField: col, 
1176                                         text: col, 
1177                                         hidden: false,
1178                                         headerAttrs: {title:desc},                              
1179                                         filter: textFilter({getFilter: (f) => { this.setState({filterEnable: true})}})
1180                                 });
1181                           }else{
1182                             tableColumnsList[type].push({name: col,
1183                         dataField: col,
1184                         text: col,
1185                                         hidden: false,
1186                                         headerAttrs: { title:desc},     
1187                         filter : customFilter(),
1188                         filterRenderer : (onFilter, column) => <AttributeFilter handleOnFilter= {this.handleOnFilter} onFilter={ onFilter } column={ column } isPageChange={this.state.isPageNumberChange} nodeType={type} columnFilter={columnFilter}/>
1189                      });
1190                           }
1191                 }
1192                 if(this.typeOfCall){
1193             this.setState({tabularAggregateColumns: tableColumnsList, tabularAggregateData: tableDataList, aggregateAttrList: attributeList,tableAggregateAliasColumns:tableAggregateAliasColumns});
1194         }else{
1195             this.setState({allTabularAggregateColumns: tableColumnsList, allTabularAggregateData: tableDataList, allAggregateAttrList: attributeList,tableAggregateAliasColumns:tableAggregateAliasColumns}, function(){if(!downloadAllCalled){downloadAllCalled = true;this.downloadAllAggregate();}});
1196         }
1197         }
1198   }
1199
1200   downloadAggregate = () =>{
1201         this.typeOfCall = true;
1202     ExportExcel.generateExcelFromTabularViewMultiTabs( this.state.tabularAggregateData, this.state.tabularAggregateColumns, 'AggregateObjects.xlsx');
1203   }
1204
1205   downloadAllAggregate = (pageRange,rangeState) =>{
1206         console.log('downloadAllAggregate>>>>>>>>>>>*',pageRange);
1207     if(pageRange){
1208           this.typeOfCall=false;
1209           let rangeModelState=(rangeState)? rangeState: false;
1210       this.setState(
1211         { pageRange: pageRange,isLoading: true,showDownloadResultsModal:rangeModelState,enableModelBusyFeedback:true},
1212         function () { this.formQueryString(false,false,false); }.bind(this)
1213       );
1214     }else{
1215       this.setState(
1216         {errorDownloadResults: false, showDownloadResultsModal: false, downloadErrorMsg:'', isLoading: false, enableModelBusyFeedback:false},
1217         function (){
1218                         ExportExcel.generateExcelFromTabularViewMultiTabs( this.state.allTabularAggregateData, this.state.allTabularAggregateColumns, 'AggregateObjects.xlsx');
1219                         this.typeOfCall = true;
1220                 }.bind(this)
1221       );
1222         } 
1223   }
1224   openDownloadRange = () =>{    
1225         this.setState({
1226           showDownloadResultsModal: true,
1227           errorDownloadResults: false,
1228           downloadErrorMsg:''});    
1229   }
1230   closeDownloadResults = () =>{
1231         this.setState({
1232                 showDownloadResultsModal: false,
1233                 enableModelBusyFeedback: false
1234                 });   
1235   }
1236   processData = (resp) => {
1237                 console.log('Response data: ' + JSON.stringify(resp.data));
1238                 this.tableFilterAliasColumns=this.formAliasFilterPropertes();
1239                 if(this.typeOfCall){
1240                         if (resp.data && resp.data.results) {
1241                                 //this.nodes = data.results;setDefaultViewName
1242                                 this.setState({
1243                                         nodes: resp.data.results,
1244                                         res: resp
1245                                 });
1246                                 this.multipleNodes = this.state.nodes.length > 1;
1247                                 //this.setState({ viewName: "CardLayout" });
1248                         }
1249                         let totalResults = 0;
1250                         let downloadCount = DOWNLOAD_ALL;
1251                         if(resp.headers) {
1252                                 totalResults = parseInt(resp.headers['total-results']);
1253                                 if(totalResults > DOWNLOAD_ALL){
1254                                         this.downloadAllTooltip = DOWNLOAD_ALL + ' results out of '+ totalResults +' results will be downloaded, Please filter results further to obtain full report';
1255                                 }else{
1256                                         this.downloadAllTooltip = (totalResults === 1) ?'Downloads ' + totalResults + ' Results' : 'Downloads all ' + totalResults + ' Results' ;
1257                                         downloadCount= totalResults;
1258                                 }
1259                                 this.setState({isLoading: false,
1260                                         totalResults: totalResults,
1261                                         totalPages: parseInt(resp.headers['total-pages']),
1262                                         showPagination: resp.headers['total-results'] > 0 ? true : false,
1263                                         showResults: resp.headers['total-results'] > 0 ? true : false,
1264                                         isInitialLoad: false,
1265                                         noResults: resp.headers['total-results'] && resp.headers['total-results'] > 0 ? false : true,
1266                                         errorResults: !resp.headers['total-results'],
1267                                         downloadCount: downloadCount
1268                                 });
1269                         }
1270                 }else{
1271                         if(resp.data && resp.data.results) {
1272                                 this.nodeResults = resp.data.results;
1273                                 let totalResults = 0;
1274                                 let totalPages = 0;
1275                                 if(resp.headers) {
1276                                         totalResults = parseInt(resp.headers['total-results']);
1277                                         totalPages = parseInt(resp.headers['total-pages']);
1278                                 }
1279                                 this.setState({totalPages:totalPages,errorDownloadResults:false,downloadErrorMsg:''},() => {this.getAllExcels()});                              
1280                         }else{
1281                                 this.nodeResults = '';
1282                                 this.setState({ isLoading: false,errorDownloadResults:true,downloadErrorMsg:error+'',enableModelBusyFeedback:false});       
1283                 }
1284                 }
1285                 GeneralCommonFunctions.scrollTo("outputBlock");
1286   }
1287
1288   close = () => {
1289                 this.setState({
1290                         showModal: false
1291                 });
1292   }
1293
1294   onClick = (event) => {
1295                 console.log('onClick');
1296   }
1297
1298   onTextAreaChange = (event) => {
1299     this.setState({value: event.target.value});
1300   }
1301
1302   onChange = (event, { newValue }) => {
1303                 console.log('onChange.newValue: ' + newValue);
1304                 let term = null;
1305                 this.setState({
1306                         value: newValue},
1307                         function () {
1308                                 console.log('onChange.selected: ' + this.state.selected);
1309                                 console.log('onChange.state value set: ' + this.state.value);
1310                                 if (this.state.value.slice(-1) === '(' || this.state.value.slice(-1) === '>') {
1311                                         //this.onSuggestionsFetchRequested(term);
1312                                         term = this.getValue(this.state.value); // this returns term, array of props or rules
1313                                         if (term) {
1314                                         console.log('onChange.term: ' + term.toString());
1315                                         }
1316                                         console.log('onChange.setting suggestions');
1317                                         this.setState({
1318                                                 suggestions: term
1319                                         });
1320                                 }else if(this.state.value === ''){
1321                                         inputValue='';
1322                                 }
1323                         }
1324                 );
1325                 // if term exists && term length > 0 - try to load suggestions
1326                 //if(term && term.length > 0){
1327                 //properties = term.map(property => {
1328                                 //return <div key={property}>{property}<br/></div>;
1329                 //});
1330                 //}
1331         }
1332
1333   getValue = (term) => {
1334                 inputValue = '';
1335                 let isStartNode = (term.split('>')).length <= 1;
1336                 console.log('getValue.term is: ' + term);
1337
1338                 let toArray = term.split(' ');
1339                 //console.log('Value' + JSON.stringify(toArray[toArray.length - 1]));
1340                 if (toArray && toArray.length > 1) {
1341                         //this.model = term;
1342                         console.log('getValue.toArray: ' + toArray.length);
1343                         this.setState({
1344                         model: term
1345                         });
1346                         term = toArray[toArray.length - 1];
1347
1348                 }
1349                 for (var i = 0; i < toArray.length - 1; i++) {
1350                         inputValue = inputValue + ' ' + toArray[i];
1351                 }
1352                 console.log('getValue.inputValue toArray: ' + inputValue);
1353                 //console.log(term.slice(-1));
1354                 if (term.slice(-1) === '(') {
1355                         console.log('getValue.detected ( property search');
1356                         var nodeVal = term.slice(0, -1);
1357                         nodeVal = nodeVal.trim();
1358                         console.log('getValue.property.nodeVal: ' + nodeVal);
1359                         var val = [];
1360                         val = this.state.nodeTypes.filter(v => v.toLowerCase().indexOf(nodeVal.toLowerCase()) > -1);
1361                         console.log('getValue.val.length: ' + val.length);
1362                         if (val.length === 0) {
1363                           nodeVal = this.state.previousNodeTypeDsl;
1364                           inputValue = inputValue + term.slice(0, -1);
1365                         }else {
1366                           inputValue = inputValue + ' ' + nodeVal;
1367                         }
1368                         console.log('getValue.inputValue property: ' + inputValue);
1369             if (nodeVal) {
1370                                 this.propertiesDsl=this.populateColumnOptions(nodeVal, isStartNode);
1371                                 this.setState({nodeTypeDsl: nodeVal,previousNodeTypeDsl:nodeVal});
1372                         }
1373                         term = this.propertiesDsl;
1374                 } else if (term.slice(-1) === '>') {
1375                         console.log('getValue.detected > edgerule search');
1376                         var nodeVal = this.state.previousNodeTypeDsl;
1377                         nodeVal = nodeVal.trim();
1378                         console.log('getValue.edgerule.nodeVal: ' + nodeVal);
1379                         var val = [];
1380
1381                         inputValue = term;
1382
1383                         this.populateEdgeRules(nodeVal);
1384                         term = traverseRulesDsl;
1385                 }
1386                 else {
1387                         //console.log('getValue.nodeTypes: ' + this.state.nodeTypes);
1388                         term = (term === '' ? this.state.nodeTypes : this.state.nodeTypes.filter(v => v.toLowerCase().indexOf(term.toLowerCase()) > -1)).slice(0, 10);
1389                 }
1390                 //console.log('getValue.term: ' + term);
1391                 return term;
1392  }
1393
1394   camelToDash = (str) =>  {
1395     console.log('camelToDash.str: ' + str);
1396                 return (str.replace(/\W+/g, '-')
1397           .replace(/([a-z\d])([A-Z])/g, '$1-$2')).toLowerCase();
1398   }
1399
1400   
1401   populateColumnOptions = (nodeType, isStartNode) =>{
1402           console.log('populateColumnOptions>>>>>nodeType',nodeType);
1403                 let propertiesDsl = [];
1404                 var result = JSON.parse(OXM);
1405                 var arrayOfTypes = result['xml-bindings']['java-types'][0]['java-type'];
1406                 //console.dir(arrayOfTypes);
1407                 var foundIndex = -1;
1408                 var searchParam = nodeType;
1409                 //if(['PSERVER', 'COMPLEX', 'CLOUDREGION', 'NETWORKPROFILE', 'VIRTUALDATACENTER'].indexOf(this.nodeType.toUpperCase()) === -1){
1410                         //searchParam = this.nodeType.substring(0, this.nodeType.length - 1);
1411                 //}
1412                 //console.log('nodeType:' + nodeType);
1413                 if (nodeType.substr(nodeType.length - 3) === 'ies') {
1414                         searchParam = nodeType.substring(0, nodeType.length - 3) + 'y';
1415                 }
1416
1417                 if (nodeType.toUpperCase() === 'LINESOFBUSINESS') {
1418                         searchParam = 'lineOfBusiness';
1419                 }
1420                 //console.log('searchParam:' + searchParam);
1421                 for (var i = 0; i < arrayOfTypes.length && foundIndex === -1; i++) {
1422                         if (arrayOfTypes[i]['xml-root-element'][0]['$']['name'] === this.camelToDash(searchParam)) {
1423                         foundIndex = i;
1424                         }
1425                 }
1426                 for (var j = 0; j < arrayOfTypes[foundIndex]['java-attributes'][0]['xml-element'].length; j++) {
1427                         let property =  arrayOfTypes[foundIndex]['java-attributes'][0]['xml-element'][j]['$']['name'];
1428                         //console.log('array' + JSON.stringify(property));
1429                         let type = arrayOfTypes[foundIndex]['java-attributes'][0]['xml-element'][j]['$']['type'];
1430                         //console.log('type: ' + type);
1431                         if (type === 'java.lang.String' || type === 'java.lang.Boolean' || type ==='java.lang.Integer' || type ==='java.lang.Long') {
1432                                 let value = '';
1433                                 if(isStartNode !== undefined){
1434                                         value = '(\'' + property + '\',\'Value\')';
1435                                 }else{
1436                                         value= property;
1437                                 }
1438                                 propertiesDsl.push(value);
1439                         }
1440                 }
1441                 //console.log('propertiesDsl: ' + propertiesDsl);
1442                 let sortedPropertiesDsl = propertiesDsl.sort(function (filter1, filter2) {
1443                         if (filter1 < filter2) {
1444                                 return -1;
1445                         } else if (filter1 > filter2) {
1446                                 return 1;
1447                         } else {
1448                                 return 0;
1449                         }
1450                 });
1451                 //console.log('sortedPropertiesDsl: ' + sortedPropertiesDsl);           
1452                 if(isStartNode !== undefined){
1453                         propertiesDsl = sortedPropertiesDsl;
1454                         //console.log('FilterList' + JSON.stringify(propertiesDsl));
1455                 }
1456                 return propertiesDsl;
1457                 
1458   }
1459   componentWillReceiveProps(nextProps) {
1460                 console.log('nextProps......', nextProps);
1461                 //console.log('this.props.....', this.props);
1462                 
1463                 var relArray = false;
1464                 if(this.props.match.params.relArray){
1465                         if(nextProps.match.params.relArray){
1466                                 if(nextProps.match.params.relArray !== this.props.match.params.relArray){
1467                                         relArray = true;
1468                                 }
1469                         }
1470                 }else{
1471                         relArray = false;
1472                 }
1473                 console.log('relArray>>>>',relArray);
1474                 this.setState({
1475                         isDSLFlow: this.props.viewName === 'BYOQ',
1476                         isSavedQueryFlow: this.props.viewName === 'Saved Queries',
1477                         showNodeModal:false
1478                 },()=>{if (nextProps.match.params.type && nextProps.match.params.propId &&
1479                         (nextProps.match.params.type !== this.props.match.params.type || 
1480                         nextProps.match.params.propId !== this.props.match.params.propId || relArray)) {
1481                         this.props = nextProps;
1482                         this.buildDynamicByoq();
1483                 }});            
1484   }
1485   populateEdgeRules = (nodeType) => {
1486                 traverseRulesDsl = [];
1487                 console.log('populateEdgeRules.nodeType: ' + nodeType);
1488                 for (var i = 0; i < this.state.edgeRules.length; i++) {
1489                         var ruleObj = this.state.edgeRules[i];
1490                         if (ruleObj.from === nodeType) {
1491                         console.log('from: ' + ruleObj.to);
1492                         traverseRulesDsl.push(ruleObj.to);
1493                         }
1494                         if (ruleObj.to === nodeType) {
1495                         console.log('to: ' + ruleObj.from);
1496                         traverseRulesDsl.push(ruleObj.from);
1497                         }
1498                 }
1499                 let traverseRulesDslSorted = traverseRulesDsl.sort(function (filter1, filter2) {
1500                         if (filter1 < filter2) {
1501                                 return -1;
1502                         } else if (filter1 > filter2) {
1503                                 return 1;
1504                         } else {
1505                                 return 0;
1506                         }
1507     });
1508                 console.log('EdgeRulesList' + JSON.stringify(traverseRulesDslSorted));
1509                 traverseRulesDsl = traverseRulesDslSorted;
1510   }
1511
1512   // Autosuggest will call this function every time you need to update suggestions.
1513   // You already implemented this logic above, so just use it.
1514   onSuggestionsFetchRequested = ({ value }) => {
1515           this.setState({
1516                 suggestions: this.getSuggestions(value)
1517           });
1518   };
1519   getAllExcels = (pageRange,rangeState) =>{
1520         console.log('getAllExcels>>>>>>>>>>>*',pageRange);
1521     if(pageRange){
1522           this.typeOfCall=false;
1523           let rangeModelState=(rangeState)? rangeState: false;
1524       this.setState(
1525         { pageRange: pageRange,isLoading: true,showDownloadResultsModal:rangeModelState,enableModelBusyFeedback:true},
1526         function () { this.formQueryString(false,false,false); }.bind(this)
1527       );
1528     }else{
1529     
1530       this.setState(
1531         {errorDownloadResults: false, showDownloadResultsModal: false, downloadErrorMsg:'', isLoading: false, enableModelBusyFeedback:false},
1532         function () { generateExcels(this.nodeResults,this.state.prevQuery);this.nodeResults='';this.typeOfCall = true;}.bind(this)
1533           );
1534     }   
1535   }
1536
1537   getTreeFromDSL = (dslQuery) =>{
1538      var treeObject = [];
1539      var payload = {dsl: dslQuery};
1540      settings['ISAPERTURE'] = true;
1541      return commonApi(settings, 'dsl/convert-query-to-tree', 'PUT', payload, 'ConvertQueryToTree')
1542                                         .then(res => {
1543                                                 console.log('res:' + res.data, 'load');
1544                                                 if(res.status === 200 || res.status === 404){
1545                                                     if(res.data.status && (res.data.status !== 200 && res.data.status !== 201 && res.data.status !== 404)){
1546                                                         this.triggerTreeError(res.data, 'treeLoad');
1547                                                         return {};
1548                                                     }else{
1549                                                         treeObject = res.data;
1550                                                         this.setState({
1551                                               treeLoadErrMsg: null
1552                                             });
1553                                            console.log("TREE OBJECT: " + JSON.stringify(treeObject));
1554                                            //set the init state
1555                                            var initNode = GeneralCommonFunctions.extractNodeDetails(treeObject.children[0], true, this.triggerTreeError, APERTURE_SERVICE);
1556                                            if(!this.state.treeLoadErrMsg || this.state.treeLoadErrMsg === ''){
1557                                                console.log(JSON.stringify(initNode));
1558                                                return initNode;
1559                                            }else{
1560                                                this.triggerTreeError(null, 'treeLoad');
1561                                                return {};
1562                                            }
1563                                        }
1564                                    }else{
1565                                      this.triggerTreeError(res.data, 'treeLoad');
1566                                      return {};
1567                                    }
1568                                         }, error=>{
1569                                             if(error.response.status === 404){
1570                                                 this.setState({enableTreeLoadBusyFeedback:false});
1571                                                 return {};
1572                                             }else{
1573                                                 this.triggerTreeError(error.response.data, 'treeLoad');
1574                                                 return {};
1575                                             }
1576                                         }).catch(error => {
1577                                             this.triggerTreeError(error, 'treeLoad');
1578                                             return {};
1579                                })
1580   }
1581   triggerTreeError = (error, type) => {
1582     console.error('[CustomDsl.jsx] error : ', JSON.stringify(error));
1583         let errMsg = '';
1584         if(error && error.status && error.message){
1585             errMsg += "Error Occurred: " + error.status + ' - ' +error.message;
1586         }else{
1587             errMsg += "Error Occurred: " + JSON.stringify(error);
1588         }
1589         console.log(errMsg);
1590         if(type === 'treeLoad' || type === 'invalidQuery'){
1591             var errorMessage = errMsg;
1592         this.setState({treeLoadErrMsg: errorMessage, enableTreeLoadBusyFeedback: false});
1593     }else{
1594         console.log('[CustomDsl.jsx] :: triggerError invoked with invalid type : ' + type);
1595     }
1596   }
1597   getConfigArrayFromDSLTree = (node, configArray, keyArray) =>{
1598
1599    var tempKey = node.name;
1600    var nodeKey;
1601    if(keyArray[tempKey]){
1602        nodeKey = tempKey + '-' + keyArray[tempKey];
1603        keyArray[tempKey] = keyArray[tempKey]++;
1604    }else{
1605        nodeKey = tempKey;
1606        keyArray[tempKey] = 1;
1607    }
1608    if(node.details && node.details.attrDetails){
1609        for (var attr in node.details.attrDetails){
1610            if(node.details.attrDetails[attr].filterType && node.details.attrDetails[attr].filterType.length > 0
1611                 && node.details.attrDetails[attr].filterType[0] !== ""){
1612                 if(!configArray[nodeKey]){
1613                     configArray[nodeKey] = {};
1614                     configArray[nodeKey].filters = [];
1615                 }
1616                 configArray[nodeKey].filters.push(attr);
1617            }
1618        }
1619    }
1620    if(node.children && node.children.length > 0){
1621        for(var i = 0; i < node.children.length; i++){
1622            configArray = this.getConfigArrayFromDSLTree(node.children[i], configArray, keyArray);
1623        }
1624    }
1625     return configArray;
1626   }
1627   handlePageChange = (pageNumber) => {
1628     console.log('[CustomDsl.jsx] HandelPageChange active page is', pageNumber);
1629         this.typeOfCall = true;
1630         if(this.state.isAggregateChecked){
1631                 this.setState(
1632                         { aggregateActivePage: pageNumber, isLoading: true, nodes: [], aggregateNodes: [],resetColumnFilters: false, isPageNumberChange: true},
1633                         function () { this.formQueryString(false,false,false); }.bind(this)
1634                         );
1635         }else{
1636                 this.setState(
1637                 { activePage: pageNumber, isLoading: true, nodes: [], aggregateNodes: [],resetColumnFilters: false, isPageNumberChange: true},
1638                 function () { this.formQueryString(false,false,false); }.bind(this)
1639                 );
1640         }
1641   }
1642   // Autosuggest will call this function every time you need to clear suggestions.
1643   onSuggestionsClearRequested = () => {
1644                 this.setState({
1645                         suggestions: []
1646                 });
1647   };
1648
1649 // https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions#Using_Special_Characters
1650   escapeRegexCharacters(str) {
1651                 return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
1652   }
1653
1654   getSuggestions = (value) => {
1655     console.log('getSuggestions.value: ' + value);
1656                 const escapedValue = this.escapeRegexCharacters(value.trim());
1657                 const regex = new RegExp('^' + escapedValue, 'i');
1658                 return nodeTypes.filter(nodeType => regex.test(nodeType));
1659   }
1660
1661
1662 // When suggestion is clicked, Autosuggest needs to populate the input
1663 // based on the clicked suggestion. Teach Autosuggest how to calculate the
1664 // input value for every given suggestion.
1665   getSuggestionValue = suggestion => suggestion;
1666
1667 // Use your imagination to render suggestions.
1668   renderSuggestion = suggestion => (
1669                 <div>
1670                         {suggestion}
1671                 </div>
1672   );
1673
1674   onSuggestionsUpdateRequested =( { value }) => {
1675     console.log('onSuggestionsUpdateRequested.value: ' + value);
1676                 this.setState({
1677                         suggestions: getSuggestions(value)
1678                 });
1679   }
1680
1681   shouldRenderSuggestions = () => {
1682                 return true;
1683   }
1684   openHistory = (nodeDisplay, nodeUri, nodeType) => { // open modal from Card
1685         console.log('history >> showModal',nodeDisplay);
1686         let historyNodeUri = (nodeUri)?nodeUri.replace('/aperture/','/'):nodeUri;
1687         let paramToPassThrough = '';
1688         if(nodeType){
1689                 this.setState({
1690                         nodeDisplay: nodeDisplay,
1691                         showHistoryModal: true,
1692                         showModelOptions:true,
1693                         enableCalendar:true,
1694                         historyType:(this.state.historyType === 'dsl') ? 'nodeState' : this.state.historyType,
1695                         focusedNodeUri: historyNodeUri,
1696                         focusedNodeType: nodeType
1697                 });
1698         }else{
1699                 this.setState({
1700                         showHistoryModal:true,
1701                         showModelOptions:false,
1702                         enableCalendar:true,
1703                         historyType : 'dsl',
1704                         focusedNodeUri: this.state.value,
1705                         focusedNodeType: nodeType
1706                 });             
1707         }
1708   }
1709   closeHistory = () => {
1710                 this.setState({
1711                         showHistoryModal: false,                        
1712                         enableCalendar:true,
1713                         historyType :'nodeState'
1714                 });
1715   }
1716   submitHistory = () => {
1717         console.log("submitting history");
1718         let paramToPassThrough = '';
1719         if(this.state.focusedNodeType){
1720                 paramToPassThrough = '/history/' + this.state.historyType +'/' + this.state.focusedNodeType + '/' + btoa(this.state.focusedNodeUri);    
1721         }else{
1722                 paramToPassThrough = '/historyQuery/' + this.state.historyType + '/' + btoa(this.state.value);
1723         }
1724     let epochStartTime = (this.state.startDate).unix();
1725         this.props.history.push(paramToPassThrough + '/' + epochStartTime * 1000);
1726   }
1727   handleDateChange = (newDate) =>{
1728     this.setState({ startDate: moment(+newDate) });
1729     console.log('[CustomDsl.jsx] handleDateChange date is ', this.state.startDate);
1730     console.log('[CustomDsl.jsx] handleDateChange date is in millis ', +this.state.startDate);
1731   }
1732
1733   setViewName(event) {
1734     console.log(event.currentTarget.value);
1735     if(this.state.isAggregate && event.currentTarget.value === 'VisualLayout'){
1736         this.formQueryString(false, false, true);
1737     }
1738     this.setState({
1739                 viewName: event.currentTarget.value
1740     });
1741   }
1742
1743   setDefaultViewName=(event)=>{
1744                 let ENVIRONMENT = GlobalExtConstants.ENVIRONMENT;
1745                 let layout =  event.target.value;
1746
1747                 if(sessionStorage.getItem(ENVIRONMENT + 'userId')) {
1748                         if (event.target.checked) {
1749                                 localStorage.setItem(ENVIRONMENT + '_' + sessionStorage.getItem(ENVIRONMENT + 'userId') + '_viewPreference', layout);
1750                         } else {
1751                                 localStorage.removeItem(ENVIRONMENT + '_' + sessionStorage.getItem(ENVIRONMENT + 'userId') + '_viewPreference');
1752                         }
1753                 }
1754
1755                 this.setState({
1756                         defaultViewName: event.target.value
1757                 });
1758                 this.baseState.viewName=event.target.value;
1759                 this.baseState.defaultViewName=event.target.value;
1760         }
1761   openNodeModal(nodeDisplay, nodeUri, nodeType){ // open modal
1762                    console.log('customdsl >> showModal');
1763                    nodeDisplay = "Node Details of " + nodeUri;
1764                    let node = null;
1765                    let found = false;
1766                    for(var j = 0; j < this.state.nodes.length && !found; j++){
1767                       if(this.state.nodes[j].url === nodeUri){
1768                           node = this.state.nodes[j];
1769                           found = true;
1770                       }
1771                    }
1772                    if(nodeDisplay && found){
1773                       this.setState({
1774                          nodeDisplay: nodeDisplay,
1775                          focusedNode: node,
1776                          showNodeModal:true
1777                       });
1778                    }else{
1779                        this.setState({
1780                        showNodeModal:true
1781                        });
1782                    }
1783     }
1784
1785     closeNodeModal = () => {
1786       this.setState({
1787         showNodeModal: false
1788       });
1789     }
1790
1791   componentDidUpdate(prevProps, prevState, snapshot) {
1792     if((this.state.isAggregate || this.state.aggregateNodes.length > 0 || this.state.nodes.length > 0) && !this.state.visualAddition){
1793         //Visualization.chart('currentState', [], [], this.state.res.data, this);
1794         this.setState({
1795                         visualAddition: true
1796         });
1797     }
1798   }
1799   setHistoryType(event) {
1800     console.log(event.target.value);
1801     let enableCalendar = false;
1802     if(event.target.value === 'nodeLifeCycle'){
1803         enableCalendar = false;
1804     }else{
1805         enableCalendar = true;
1806     }
1807     this.setState({
1808                 historyType: event.target.value,
1809                 enableCalendar: enableCalendar
1810     });
1811     console.log(this.state.enableCalendar);
1812   }
1813   loadBulkCallback=(loadQueryList)=>{
1814         console.log('Start:Load bulk Callback>>>>>>');
1815         let filterEntriesList=[];
1816         let filterTemplateHeaderList=[];
1817         let filterTemplateErrorList=[];
1818         let nodeTypeOfDslTemplateList=[];
1819         let templateQueryList=[];
1820         let valueList=[];
1821         this.dslObjectList=[];
1822         this.nodeTypeArrayList=[];
1823         this.tempDslQueryList=[];
1824         this.templateErrorList={};
1825         let isAggregateCheckedList=[];
1826         let associatedNodesEnabledList=[];
1827         let queryNameList=[];
1828         let queryDescriptionList=[];
1829         let categoryList=[];
1830         let isPublicCheckedList=[];
1831         let queryIdList=[];
1832         let filterTypeDisplayList=[];
1833         let isCommunitySharedList = [];
1834         let staticTemplateFiltersList=[];
1835         for(var idx=0;idx<loadQueryList.length;idx++){
1836                 let splitString = loadQueryList[idx].split('||');
1837                 let name = splitString[0];
1838                 let description = splitString[1];
1839                 let category=(splitString[2] !== 'undefined')? splitString[2]:'';
1840                 let dsl = splitString[3];
1841                 let isAggregate = splitString[4];
1842                 let type = splitString[5];
1843                 let queryId = splitString[6];
1844                 let isCommunityShared = splitString[7];
1845                 let templateDetails = splitString[8];
1846                 if(name !== '' && description !== '' && this.state.isSavedQueryFlow){
1847                     var staticTemplateFilters = templateDetails;
1848             if(staticTemplateFilters.length > 0){
1849               staticTemplateFilters = JSON.parse(staticTemplateFilters);
1850             }else{
1851               staticTemplateFilters = [];
1852             }
1853             staticTemplateFiltersList.push(staticTemplateFilters);
1854                         queryNameList.push(name);
1855                         queryIdList.push(queryId);
1856                         queryDescriptionList.push(description);
1857                         isPublicCheckedList.push(type === 'public');
1858                         categoryList.push(category);
1859                         isCommunitySharedList.push(isCommunityShared);                  
1860                 }
1861                 associatedNodesEnabledList.push(false);
1862                 if(isAggregate === "true"){
1863                         isAggregateCheckedList.push(true);
1864                 }else{
1865                         isAggregateCheckedList.push(false);             
1866                 }
1867                 filterTypeDisplayList.push({'default':'Filter Type'});
1868                 this.setState({
1869                         queryNameList:queryNameList,
1870                         queryDescriptionList:queryDescriptionList,
1871                         categoryList:categoryList,
1872                         isPublicCheckedList: isPublicCheckedList,
1873                         queryIdList: queryIdList,
1874                         filterTemplateEntries:[],
1875                         filterTemplateError: false,
1876                         isTypeahead: false,
1877                         isAggregateCheckedList: isAggregateCheckedList,
1878                         associatedNodesEnabledList: associatedNodesEnabledList,
1879                         filterTypeDisplayList: filterTypeDisplayList,
1880                         downloadTemplateStatus:false,
1881                         failedDownloadedTemplate:[],
1882                         failedDownloadedTemplateMsg:'',
1883                         failedEmailTemplateMsg:'',
1884                         emailTriggerMsg:'',
1885                         isMergedTabsChecked: false,
1886                         staticTemplateFiltersList: staticTemplateFiltersList
1887                 });
1888                 
1889                 if(this.state.isSavedQueryFlow){
1890                                                         
1891                         dsl=atob(dsl).replace('<pre>','').replace('</pre>','');                 
1892                         this.dslObject={};
1893                         this.nodeTypeArray=[];
1894                                 
1895                         var limitPattern = /limit[\s]\d+|limit\d+/ig;
1896                         var limitkey = dsl.match(limitPattern);
1897                         if(limitkey){
1898                                 dsl = dsl.replace(limitkey[limitkey.length-1],'').trim();
1899                         }
1900                         dsl = this.alterDslQueryByRemoveSpaces(dsl);
1901                         //create placeholders for NodeTypes with Propand Propvalues
1902                         this.tempDslQuery=this.formTempDslQuery(dsl);
1903                         this.tempDslQueryList.push(this.tempDslQuery);
1904                         //Preparinga Json Object to render into Placeholder             
1905                         this.contructDslNodes(dsl,'node',false,false,false,false);
1906                         //Query to replace placeholders with JSON Object values depends on Flow either SavedQuery or TableFilters
1907                         let query=this.formTemplateQuery('savedQuery',idx,true);
1908                         query=query.replace(/\'(as)\'/g,'\' as \'').replace(/\(\'\s(as)\s\'\)/g,'(\'as\')');
1909                         if(limitkey){
1910                                 query+=' '+limitkey[limitkey.length-1];         
1911                         }       
1912                         let filterEntries=[];
1913                         let filterTemplateHeader={};
1914                         var errorOccurred=false;
1915                         Object.keys(this.dslObject).map((key)=>{
1916                                 filterEntries.push(this.dslObject[key]['filterEntries'][0]);
1917                                 filterTemplateHeader[key]= {}
1918                                 filterTemplateHeader[key]=this.dslObject[key]['filterTemplateHeader'][key];
1919                                 if(!errorOccurred){
1920                                         errorOccurred=this.dslObject[key]['errorOccurred'];
1921                                 }       
1922                         });                     
1923                         filterEntriesList.push(filterEntries);
1924                         filterTemplateHeaderList.push(filterTemplateHeader);
1925                         filterTemplateErrorList.push(errorOccurred);
1926                         nodeTypeOfDslTemplateList.push(this.nodeTypeArray);
1927                         templateQueryList.push(query);
1928                         valueList.push(dsl);
1929                         this.dslObjectList.push(this.dslObject);
1930
1931                 }
1932         }
1933         this.setState({ valueList: valueList, 
1934                 templateQueryList: templateQueryList, 
1935                 filterTemplateEntriesList: filterEntriesList,
1936                 filterTemplateHeaderList:filterTemplateHeaderList,
1937                 filterTemplateErrorList: filterTemplateErrorList,
1938                 nodeTypeOfDslTemplateList:nodeTypeOfDslTemplateList,            
1939                 isAggregateCheckedList: isAggregateCheckedList,
1940                 associatedNodesEnabledList: associatedNodesEnabledList,
1941                 isInitialLoad:false
1942         },()=>{GeneralCommonFunctions.scrollTo('templateList');});
1943   }
1944   loadCallback = (name, description, category, dslQuery, isAggregate, type, queryId, isCommunityShared, id, templateDetails, makeCall) =>{
1945         let filterEntriesList=[];
1946         let filterTemplateHeaderList=[];
1947         let filterTemplateErrorList=[];
1948         let nodeTypeOfDslTemplateList=[];
1949         let templateQueryList=[];
1950         let valueList=[];
1951         this.dslObjectList=[];
1952         this.nodeTypeArrayList=[];
1953         this.tempDslQueryList=[];
1954         this.templateErrorList={};
1955         let isAggregateCheckedList=[];
1956         let associatedNodesEnabledList=[];
1957         let queryNameList=[];
1958         let queryDescriptionList=[];
1959         let categoryList=[];
1960         let isPublicCheckedList=[];
1961         let queryIdList=[];
1962         let filterTypeDisplayList=[];
1963         let isCommunitySharedList=[];
1964         let staticTemplateFiltersList=[];
1965         let idx=parseInt(id);
1966         if(isNaN(idx)){
1967                 idx=0;
1968         }
1969     if(name !== '' && description !== '' && this.state.isSavedQueryFlow){               
1970                 queryNameList.push(name);
1971                 queryIdList.push(queryId);
1972                 queryDescriptionList.push(description);
1973                 isPublicCheckedList.push(type === 'public');
1974                 var staticTemplateFilters = templateDetails;
1975         if(staticTemplateFilters.length > 0){
1976           staticTemplateFilters = JSON.parse(staticTemplateFilters);
1977         }else{
1978           staticTemplateFilters = [];
1979         }
1980         staticTemplateFiltersList.push(staticTemplateFilters);
1981                 categoryList.push(category);
1982                 isCommunitySharedList.push(isCommunityShared);
1983         this.setState({
1984                   queryNameList:queryNameList,
1985                   queryDescriptionList:queryDescriptionList,
1986                   categoryList:categoryList,
1987                   isPublicCheckedList: isPublicCheckedList,
1988                   isCommunitySharedChecked: isCommunityShared === "true",
1989                   queryIdList: queryIdList,
1990                   isCommunitySharedList:isCommunitySharedList,
1991                   staticTemplateFiltersList: staticTemplateFiltersList,
1992                   downloadTemplateStatus:false,
1993                   failedDownloadedTemplate:[],
1994                   failedDownloadedTemplateMsg:'',
1995                   failedEmailTemplateMsg:'',
1996                   emailTriggerMsg:'',
1997                   isMergedTabsChecked: false,
1998                   isGenerateEmailChecked: false
1999         });
2000     }
2001     //reset any filter template forms
2002         this.setState({ filterTemplateEntries: [], filterTemplateError: false, isTypeahead: false});
2003         associatedNodesEnabledList.push(false);
2004         let associatedNodesEnable=false;
2005         let isAggregateChecked=false;
2006     if(isAggregate === "true"){
2007                 isAggregateCheckedList.push(true);
2008                 isAggregateChecked=true;
2009     }else{
2010         isAggregateCheckedList.push(false);             
2011     }
2012     this.setState({ isAggregateCheckedList: isAggregateCheckedList, associatedNodesEnabledList: associatedNodesEnabledList,isAggregateChecked:isAggregateChecked,associatedNodesEnabled:associatedNodesEnable});        
2013     if(this.state.isSavedQueryFlow && !makeCall){
2014         this.loadTemplateForm(atob(dslQuery).replace('<pre>','').replace('</pre>',''),idx);
2015     }else{
2016                 this.setState({viewName: this.state.defaultViewName,
2017                        activePage: 1,
2018                        aggregateActivePage: 1});
2019         this.buildDynamicByoq(atob(dslQuery).replace('<pre>','').replace('</pre>',''), makeCall);
2020     }
2021     if(this.state.isDSLFlow){
2022         GeneralCommonFunctions.scrollTo("jumbotron");
2023     }else if(this.state.isSavedQueryFlow){
2024         GeneralCommonFunctions.scrollTo("templateList");
2025     }
2026   }
2027
2028   editCallback = (name, description, category, dsl, isAggregateStr, type, queryId, isCommunityShared, templateDetails) =>{
2029         //Save stated of loaded queries
2030         this.state.valuePreviousState = this.state.value;
2031         this.state.isAggregateCheckedPreviousState = this.state.isAggregateChecked;
2032         this.state.isCommunitySharedCheckedPreviousState = this.state.isCommunitySharedChecked;
2033     this.state.associatedNodesEnabledPreviousState = this.state.associatedNodesEnabled;
2034
2035         let isAggregateChecked = false;
2036         let isCommunitySharedChecked = false;
2037         let associatedNodesEnabled = false;
2038
2039         if(isAggregateStr === 'true'){
2040                 isAggregateChecked = true;
2041                 associatedNodesEnabled = true;
2042         }
2043
2044         if(isCommunityShared === 'true'){
2045         isCommunitySharedChecked = true;
2046     }
2047
2048     var staticTemplateFilters = templateDetails;
2049     if(staticTemplateFilters.length > 0){
2050         staticTemplateFilters = JSON.parse(staticTemplateFilters);
2051     }else{
2052         staticTemplateFilters = [];
2053     }
2054     this.getTreeFromDSL(dsl).then(tree => {
2055          this.setState({
2056                         enableTreeLoadBusyFeedback: false,
2057                         dslConfigArray: this.getConfigArrayFromDSLTree(tree, [], []),
2058                         showSaveModal: true,
2059                         saveSuccessfulMsg: false,
2060                         isPublicChecked: type === 'public',
2061                         isEditModal:true,
2062                         queryName:name,
2063                         queryDescription:description,
2064                         category:category,
2065                         isAggregateChecked: isAggregateChecked,
2066                         isCommunitySharedChecked: isCommunitySharedChecked,
2067                         associatedNodesEnabled: associatedNodesEnabled,
2068                         value: dsl,
2069                         queryId: queryId,
2070                         staticTemplateFilters: staticTemplateFilters
2071                         });
2072     });
2073   }
2074
2075   saveTemplate = (idx) => {
2076           var saveModal = () => {
2077                 this.setState(
2078                         {
2079                                   showSaveModal: true,
2080                                   saveSuccessfulMsg: false,
2081                                   isPublicChecked: this.state.isPublicChecked,
2082                                   isEditModal:false,
2083                                   queryName:'',
2084                                   queryDescription:'',
2085                                   category:'',
2086                                   queryId:'',
2087                                   isPublicChecked: this.state.isPublicCheckedList[idx],
2088                                   isAggregateChecked: this.state.isAggregateCheckedList[idx],
2089                                   enableTreeLoadBusyFeedback: true
2090                         });
2091                 this.getTreeFromDSL(this.state.value).then(tree => {
2092                 this.setState({enableTreeLoadBusyFeedback: false, dslConfigArray: this.getConfigArrayFromDSLTree(tree, [], [])});
2093         });
2094           }
2095           this.populateTemplate(false, saveModal, idx);
2096   }
2097
2098   runTemplate = (idx) =>{
2099     this.populateTemplate(true, null, idx);
2100   }
2101   submitEditAndRunDSL = () =>{
2102     this.setState({ showEditModal: false, value: this.state.editModel,aggregateActivePage:1,activePage:1 }, () => this.formQueryString(false,false,false));
2103   }
2104   showEditDSLModal = (idx) => {
2105     console.log("enabling DSL edit modal");
2106     var openModal = () => {
2107         this.setState({ editModel: this.state.value, enableTreeLoadBusyFeedback: true, showEditModal: true });
2108     }
2109     this.populateTemplate(false, openModal, idx);
2110   }
2111   closeEditDSLModal = () => {
2112     console.log("closing DSL edit modal");
2113     this.setState({ showEditModal: false, enableTreeLoadBusyFeedback: false });
2114   }
2115   bindEdits = (e) => {
2116     this.setState({ editModel: e.target.value });
2117   }
2118   populateTemplate = (shouldRun, callback, indx) =>{
2119         console.log('CustomDSL:populateTemplate this.state>>>>>>>>>>>>>>>>>>>*',this.state);
2120         let query=this.formFinalTemplateQuery(indx);
2121         console.log('CustomDSL:query>>>>>>>>>*',query);
2122         console.log('CustomDSL:query>>>>>>>>>BTOA*',btoa(query));
2123     this.setState({ value: query,aggregateActivePage:1,activePage:1}, () => {if(shouldRun){this.formQueryString(false,false,false)}else{callback()}});
2124   }
2125   formFinalTemplateQuery = (indx)=>{
2126         console.log('formFinalTemplateQuery>> forming finalQuery before Run scenarios>>>>');
2127         var query = this.state.templateQueryList[indx];
2128         for(var i = 0; i < this.state.filterTemplateEntriesList[indx].length; i++){
2129                 let filterTemplateEntries=this.state.filterTemplateEntriesList[indx][i];
2130                 Object.keys(filterTemplateEntries).map((key)=>{
2131                         Object.keys(filterTemplateEntries[key]).map((entry)=>{
2132                                 let templateEntry=filterTemplateEntries[key][entry];
2133                                 if(templateEntry.name !== ''){
2134                                         let templateFilterQuery = "'" + templateEntry.name + "','" + templateEntry.value + "'";
2135                                         console.log('Before templateFilterQuery>>>>>',templateFilterQuery);
2136                                         let valueArray=templateEntry.value.split('^');
2137                                         let typeArray=templateEntry.type.split('^');
2138                                         templateFilterQuery = "'" + templateEntry.name + "'";
2139                                         let templatekeyValues='';
2140                                         for(var x=0;x<valueArray.length;x++){
2141                                                 if(valueArray[x] !==''){
2142                                                         if(templatekeyValues === ''){                                                                   
2143                                                                 templatekeyValues = (this.state.enableRealTime)?typeArray[x] +"('" + valueArray[x] + "')":"'"+valueArray[x]+"'";
2144                                                         }else{
2145                                                                 templatekeyValues = (this.state.enableRealTime)?templatekeyValues+","+typeArray[x] +"('" + valueArray[x] + "')":templatekeyValues+",'"+ valueArray[x] + "'";
2146                                                         }
2147                                                 }
2148                                         }
2149                                         templateFilterQuery=templateFilterQuery+","+templatekeyValues;
2150                                         console.log('templateFilterQuery>>>>>',templateFilterQuery);
2151                                         query = query.replace('$' + (templateEntry.templateKey + 1),templateFilterQuery);
2152                                         query = query.replace(/\"/g,'\'');
2153                                 }
2154                         })                      
2155                 });             
2156         }
2157         return query;
2158   }
2159   stripFirstCharacter=(str)=>{
2160         return str.substr(1);
2161   }
2162   stripLastCharacter=(str)=>{
2163         return str.substr(0, str.length - 1);
2164   }
2165   stripFirstTwoCharacter(str){
2166         return str.substr(2);
2167   }
2168   updateTemplateFilterValues=(key,templateKey,value,id,idx)=>{
2169         if(value!==''){
2170           var filterTemplateEntriesList = this.state.filterTemplateEntriesList;
2171           var filterTemplateHeaderList=this.state.filterTemplateHeaderList;
2172           var filterMap = filterTemplateEntriesList[idx];
2173           var filterTemplateHeader=filterTemplateHeaderList[idx];
2174           let idArray=id.split('_');
2175           let ind=parseInt(idArray[idArray.length-1]);
2176           let finalSelectedProp='';
2177           let existing=false;
2178           console.log(ind+'<<<updateTemplateFilterValues>>>>'+key+'<><>',value);
2179           console.log(templateKey+'filterMap>>>>>>>>>>>>>>>>',filterMap);
2180           Object.keys(filterMap).forEach((index) =>{
2181                   if(filterMap[index][key]){
2182                           Object.keys(filterMap[index][key]).forEach((i)=>{
2183                                   if(filterMap[index][key][i].templateKey === templateKey){
2184                                           console.log(key+'<<filterMap[index][key][templateKey]>>>'+filterMap[index][key][i]);
2185                                           let filterValue=filterMap[index][key][i].value.split('^');
2186                                           filterValue[ind]=value;
2187                                           filterMap[index][key][i].value=filterValue.join('^');
2188                                           console.log('Updated Filtered Template Entries map' + JSON.stringify(filterMap));                                             
2189                                           if(filterMap[index][key][i].name !== '' ){
2190                                                   filterTemplateHeader[key]['propName'] = filterMap[index][key][i].name;
2191                                                   existing =true;
2192                                           }else{
2193                                                   console.log('set listname >>>>***',filterTemplateHeader[key]['propName']);
2194                                                   finalSelectedProp=filterTemplateHeader[key]['propName'];
2195                                                   let status=false;
2196                                                   if(filterTemplateHeader[key]['propName'] !== this.state.filterDisplay){                                                         
2197                                                         filterMap[index][key][i].name= filterTemplateHeader[key]['propName'];
2198                                                         status=true;
2199                                                   }else{
2200                                                         filterMap[index][key][i].name= 'ERROR';
2201                                                         if(!(this.templateErrorList[idx] && this.templateErrorList[idx].length>0)){
2202                                                                 this.templateErrorList[idx]=[];
2203                                                         }
2204                                                         this.templateErrorList[idx].push(key);
2205                                                   }
2206                                                   let selectedProp=[];
2207                                                   console.log('filterTemplateHeader[key][selectedProp]>>>>',filterTemplateHeader[key]['selectedProp']);
2208                                                   if(filterTemplateHeader[key]['selectedProp'] && status){
2209                                                           selectedProp=filterTemplateHeader[key]['selectedProp'];
2210                                                           let indSelect= selectedProp.indexOf(filterTemplateHeader[key]['propName']);
2211                                                           if(indSelect !== -1){
2212                                                                   selectedProp=selectedProp.splice(indSelect,1);
2213                                                                   filterTemplateHeader[key]['selectedProp']=selectedProp;
2214                                                           }                                     
2215                                                   }                                                                     
2216                                           }                             
2217                                           filterTemplateHeader[key]['enableAnd'] = true;
2218                                           this.updateSavedQueryTemplate('add',key,templateKey,filterMap,filterTemplateHeader,idx);
2219                                   }
2220                           });                           
2221                   }
2222           });
2223         }
2224         // this.setState({filterTemplateError: true});     
2225 }
2226 updateSavedQueryTemplate=(action,key,templatekey,templateMaps,templateHeader,idx)=>{
2227                 console.log(action+'updateSavedQueryTemplate>>>>>>>>>>>>>*');
2228                 let templateEntriesList = this.state.filterTemplateEntriesList;
2229                 let filterTemplateHeaderList=this.state.filterTemplateHeaderList;
2230                 let templateEntries = templateEntriesList[idx];
2231                 let filterTemplateHeader= filterTemplateHeaderList[idx];
2232                 let finalSelectedProp='';
2233                 idx=parseInt(idx);
2234                 if(templateMaps){
2235                   templateEntries=templateMaps;
2236                 }
2237                 if(templateHeader){
2238                   filterTemplateHeader=templateHeader
2239                 }
2240                 let templateQuery = this.state.templateQueryList[idx];
2241                 if(templateQuery.charAt(templateQuery.length-1) !== ']'){
2242                   templateQuery=templateQuery+',';
2243                 }       
2244                 let keyact=isNaN(parseInt(key.substr(key.length-2,key.length-1)));
2245                 console.log('keyact>>>>****',keyact);
2246                 console.log('TemplateQuery>>>&&*',templateQuery);
2247                 let nodeInd=0;
2248                 let tempkey =key;
2249                 if(!keyact){
2250                           let actKey=key.split('-');
2251                           nodeInd=parseInt(actKey[actKey.length-1]);
2252                           actKey.splice(actKey.length-1,1);
2253                           tempkey=actKey.join('-');
2254                 }
2255                 let dslObject=this.dslObjectList[idx];
2256                 if(action === 'add'){
2257                         Object.keys(dslObject).map((nodekey)=>{
2258                           if(nodekey === key){
2259                                   let tempEntries=[];                    
2260                                   Object.keys(templateEntries).map((index) =>{if(templateEntries[index][key] && nodekey === key){ tempEntries= templateEntries[index][key]}});
2261                                   console.log('tempEntries>>>>',tempEntries); 
2262                                   dslObject[nodekey]['templateEntries']=tempEntries;
2263                                   dslObject[nodekey]['filterTemplateHeader']=filterTemplateHeader[nodekey];
2264                           }               
2265                         })
2266                 }else{
2267                   let findEntry=true;
2268                   Object.keys(templateEntries).map((index) =>{
2269                           console.log('templateEntries[index][key]??????',templateEntries[index][key]);
2270                           if(templateEntries[index][key]){
2271                                   Object.keys(templateEntries[index][key]).map((i)=>{
2272                                           console.log(i+'templateEntries[index][key][i].templateKey>>>',templateEntries[index][key][i]);
2273                                           if(findEntry && templateEntries[index][key][i].templateKey === templatekey){
2274                                                   findEntry=false;
2275                                                   let name = templateEntries[index][key][i].name;
2276                                                   finalSelectedProp=name;
2277                                                   templateEntries[index][key].splice(i,1);
2278                                                   filterTemplateHeader[key]['enableAnd'] = true;
2279                                                   filterTemplateHeader[key]['propName'] = this.state.filterDisplay;
2280                                                   let selectedProp=[];
2281                                                   console.log('filterTemplateHeader[key][selectedProp]???????',filterTemplateHeader[key]['selectedProp']);
2282                                                   if(filterTemplateHeader[key]['selectedProp']){
2283                                                           selectedProp=filterTemplateHeader[key]['selectedProp'];
2284                                                           let ind= selectedProp.indexOf(name);
2285                                                           if(ind !== -1){
2286                                                                   selectedProp=selectedProp.splice(ind,1);
2287                                                                   filterTemplateHeader[key]['selectedProp']=selectedProp;
2288                                                           }     
2289                                                   }
2290                                                   if(name=='ERROR'){
2291                                                         if(this.templateErrorList[idx] && this.templateErrorList[idx].length>0){
2292                                                                 this.templateErrorList[idx].pop();
2293                                                         }                                                       
2294                                                   }
2295                                                   console.log('selectedProp>>>>',filterTemplateHeader[key]['selectedProp']);
2296                                           }
2297                                   });   
2298                           }
2299                   });
2300                   Object.keys(dslObject).map((nodekey)=>{
2301                           if(nodekey === key && !findEntry){
2302                                 let tempEntries=[];                      
2303                                 Object.keys(templateEntries).map((index) =>{if(templateEntries[index][key] && nodekey === key){ tempEntries= templateEntries[index][key]}});
2304                                 console.log('Delete tempEntries>>>>',tempEntries); 
2305                                 dslObject[nodekey]['templateEntries']=tempEntries;
2306                                 dslObject[nodekey]['filterTemplateHeader']=filterTemplateHeader[nodekey];
2307                           }               
2308                   })
2309                 }
2310                 console.log(action+' .......Update Saved ***************this.dslObject',dslObject);
2311                 Object.keys(dslObject).map((nodekey)=>{
2312                           //console.log(nodekey+'this.dslObject[nodekey][0]>>>>>',dslObject[nodekey][0]);
2313                           //console.log('key>>>>',key);
2314                           if(nodekey === key && dslObject[nodekey][0]){
2315                                   Object.keys(templateEntries).map((index) =>{
2316                                           console.log('templateEntries[index][key]>>>>',templateEntries[index][key]);
2317                                           if(templateEntries[index][key]){
2318                                                  let props='{';
2319                                                  Object.keys(templateEntries[index][key]).map((i)=>{
2320                                                         console.log(i+'templateEntries[index][key]>>>>',templateEntries[index][key][i]);
2321                                                           let prop='';
2322                                                           let newProps=(parseInt(i)!==0)?',\''+templateEntries[index][key][i]['name']+'\'':'\''+templateEntries[index][key][i]['name']+'\'';    
2323                                                           props+=newProps;
2324                                                           if(templateEntries[index][key][i].templateKey === templatekey){
2325                                                                   let name=templateEntries[index][key][i]['name']
2326                                                                   let value=templateEntries[index][key][i]['value'].split('^');
2327                                                                   let type=templateEntries[index][key][i]['type'].split('^');
2328                                                                   prop='(\''+name+'\',';
2329                                                                   for(var x=0;x<value.length;x++){
2330                                                                           if(this.state.enableRealTime){
2331                                                                                   prop+=type[x]+'(\''+value[x]+'\')';
2332                                                                                   if(x===value.length-1){
2333                                                                                           prop+=')';
2334                                                                                   }else{
2335                                                                                           prop+=',';
2336                                                                                   }     
2337                                                                           }else{
2338                                                                                   prop+='\''+value[x]+'\'';
2339                                                                                   if(x===value.length-1){
2340                                                                                           prop+=')';
2341                                                                                   }else{
2342                                                                                           prop+=',';
2343                                                                                   }
2344                                                                           }
2345                                                                   }
2346                                                                   let values=dslObject[nodekey][0]['values'];
2347                                                                   //console.log('values>>>>>',values);
2348                                                                   if(values && values.length>0){
2349                                                                         let findState=false;
2350                                                                         let errorPropMsg=null;                                                                  
2351                                                                         for(var n=0;n<values.length;n++){
2352                                                                                 if(values[n].indexOf('!(\''+name+'\'') !==-1){
2353                                                                                         values[n]='!'+prop;
2354                                                                                         findState=true;
2355                                                                                 }else if(values[n].indexOf('(\''+name+'\'') !==-1){
2356                                                                                         values[n]=prop;
2357                                                                                         findState=true;
2358                                                                                 }
2359                                                                                 if(values[n].indexOf('(\'ERROR\',') !==-1){
2360                                                                                         errorPropMsg=n;
2361                                                                                 }
2362                                                                         }
2363                                                                         if(errorPropMsg){
2364                                                                                 values.splice(errorPropMsg,1);
2365                                                                         }
2366                                                                         if(!findState){
2367                                                                                 values.push(prop);
2368                                                                         }
2369                                                                         dslObject[nodekey][0]['values']=values;                                                                 
2370                                                                  }else{
2371                                                                         dslObject[nodekey][0]['values']=[];
2372                                                                         dslObject[nodekey][0]['values'].push(prop);
2373                                                                  }
2374                                                                  //console.log(prop+'this.dslObject[nodekey][0][values]>>>>',dslObject[nodekey][0]['values']);
2375                                                           }
2376                                                   });
2377                                                   props+='}';                                             
2378                                                   if(action!=='add' && dslObject[nodekey][0]['values']){
2379                                                           dslObject[nodekey][0]['values'].splice(idx,1);                                                                
2380                                                   }
2381                                           }
2382                                   });
2383                           }               
2384                 });
2385                 //console.log('After Setting ***************this.dslObject',dslObject);         
2386                 this.dslObjectList[idx]=dslObject;
2387                 let queryList=this.state.templateQueryList;
2388                 let dslquery=queryList[idx];
2389                 var limitPattern = /limit[\s]\d+|limit\d+/ig
2390                 var limitkey = dslquery.match(limitPattern);            
2391                 //this.tempDslQuery=this.formTempDslQuery(dsl);
2392                 let query=this.formTemplateQuery('savedQuery',idx);
2393                 query=query.replace(/\'(as)\'/g,'\' as \'').replace(/\(\'\s(as)\s\'\)/g,'(\'as\')');
2394                 if(limitkey){
2395                         query+=' '+limitkey[limitkey.length-1];         
2396                 }       
2397                 console.log('query>>>>>>>>>>>>>',query);
2398                 queryList[idx]=query;
2399                 templateEntriesList[idx]=templateEntries;
2400                 filterTemplateHeaderList[idx]=filterTemplateHeader;
2401                 this.setState({filterTemplateEntriesList:templateEntriesList,filterTemplateHeaderList:filterTemplateHeaderList,templateQueryList:queryList}); 
2402           
2403   }     
2404   capturingGroups=(dsl)=>{
2405         var capturedGroups=[];
2406         let findGroup=true;
2407         var block = dsl;
2408         do{
2409                 var startIndex = block.indexOf('['),/* index of first bracket */
2410                 currPos = startIndex,
2411                 openBrackets = 0,
2412                 stillSearching = true,
2413                 waitForChar = false;
2414                 if(currPos === -1){
2415                         findGroup=false;
2416                 }
2417                 while (stillSearching && currPos <= block.length) {
2418                   var currChar = block.charAt(currPos);
2419                   switch (currChar) {
2420                           case '[':
2421                                 openBrackets++; 
2422                                 break;
2423                           case ']':
2424                                 openBrackets--;
2425                                 break;                    
2426                         }                 
2427                   currPos++ 
2428                   if (openBrackets === 0) { stillSearching = false; } 
2429                 }
2430                 console.log('capturingGroups>>>>>>>>>>>>',block.substring(startIndex , currPos));
2431                 if(block.substring(startIndex , currPos) !==''){
2432                         capturedGroups.push(block.substring(startIndex , currPos));
2433                         block=block.replace(block.substring(startIndex , currPos),'#$')
2434                 }
2435         }while(findGroup);              
2436         return capturedGroups;
2437   }
2438   formTempDslQuery=(dsl) =>{
2439         let tempQuery='';
2440         tempQuery=dsl.replace(/\!\((?:[^>)(]|\((?:[^)(]+)\))*\)/g,'').replace(/\((?:[^>)(]|\((?:[^)(]+)\))*\)/g,'').replace(/\{(.*?)\}/g,'').replace(/\*/g,'').trim('')+',';
2441         tempQuery = tempQuery.replace(/\s+/g, '');
2442         tempQuery=tempQuery.replace(/[a-zA-Z0-9*\-]/g,'#').replace(/\!\!/g,'!').replace(/\!\>/g,'>');
2443         tempQuery=tempQuery.replace(/\#(.*?)(?=\>|\!|\(|\)|\,|\])/g,'#').trim('');
2444         tempQuery=this.stripLastCharacter(tempQuery);
2445         return tempQuery;
2446   }
2447   loadTemplateForm=(dsl,idx) =>{
2448         console.log('loadTemplateForm>>>idx>>>>',idx);
2449         this.dslObject={};
2450         this.nodeTypeArray=[];
2451         var limitPattern = /limit[\s]\d+|limit\d+/ig;
2452         var limitkey = dsl.match(limitPattern);
2453         if(limitkey){
2454                 dsl = dsl.replace(limitkey[limitkey.length-1],'').trim();
2455         }
2456         dsl = this.alterDslQueryByRemoveSpaces(dsl);
2457         //create placeholders for NodeTypes with Propand Propvalues
2458         this.tempDslQuery=this.formTempDslQuery(dsl);
2459         this.tempDslQueryList.push(this.tempDslQuery);
2460         //Preparinga Json Object to render into Placeholder             
2461         this.contructDslNodes(dsl,'node',false,false,false,false);
2462         console.log('dsl>>>>>>>>>>>>>',dsl);
2463         //Query to replace placeholders with JSON Object values depends on Flow either SavedQuery or TableFilters
2464         let query=this.formTemplateQuery('savedQuery',idx,true);
2465         query=query.replace(/\'(as)\'/g,'\' as \'').replace(/\(\'\s(as)\s\'\)/g,'(\'as\')');
2466         if(limitkey){
2467                 query+=' '+limitkey[limitkey.length-1];         
2468         }       
2469         let filterEntries=[];
2470         let filterTemplateHeader={};
2471         var errorOccurred=false;
2472         console.log('before setting DSLOBJECT>>',this.dslObject);
2473         Object.keys(this.dslObject).map((key)=>{
2474                 filterEntries.push(this.dslObject[key]['filterEntries'][0]);
2475                 filterTemplateHeader[key]= {}
2476                 filterTemplateHeader[key]=this.dslObject[key]['filterTemplateHeader'][key];
2477                 if(!errorOccurred){
2478                         errorOccurred=this.dslObject[key]['errorOccurred'];
2479                 }       
2480         });     
2481         let filterEntriesList=[];
2482         let filterTemplateHeaderList=[];
2483         let filterTemplateErrorList=[];
2484         let nodeTypeOfDslTemplateList=[];
2485         let templateQueryList=[];
2486         let valueList=[];
2487         if(idx === 0){
2488                 this.setState({ valueList: [], 
2489                         templateQueryList: [], 
2490                         filterTemplateEntriesList: [],
2491                         filterTemplateHeaderList:[],
2492                         filterTemplateErrorList: [],
2493                         nodeTypeOfDslTemplateList:[]
2494                 });
2495         }
2496         filterEntriesList.push(filterEntries);
2497         filterTemplateHeaderList.push(filterTemplateHeader);
2498         filterTemplateErrorList.push(errorOccurred);
2499         nodeTypeOfDslTemplateList.push(this.nodeTypeArray);
2500         templateQueryList.push(query);
2501         valueList.push(dsl);
2502         this.dslObjectList.push(this.dslObject);    
2503         this.setState({ valueList: valueList, 
2504                 templateQueryList: templateQueryList, 
2505                 filterTemplateEntriesList: filterEntriesList,
2506                 filterTemplateHeaderList:filterTemplateHeaderList,
2507                 filterTemplateErrorList: filterTemplateErrorList,
2508                 nodeTypeOfDslTemplateList:nodeTypeOfDslTemplateList,
2509                 isInitialLoad:false
2510         },()=>{GeneralCommonFunctions.scrollTo('templateList');});
2511         
2512   }
2513  formTemplateQuery=(flow,idx,state)=>{
2514         let query='';
2515         let count = 0;
2516         let tempDslQueryArr=(idx !== undefined && !state)?this.tempDslQueryList[idx].split('#'):this.tempDslQuery.split('#');
2517         let newCustomQuery=(idx !== undefined && !state)?this.dslObjectList[idx]:this.dslObject;
2518         Object.keys(newCustomQuery).map((key)=>{
2519                 query='';
2520                 let newDslObject=newCustomQuery[key][0];
2521                 let filterValues='';
2522                 if(newDslObject){
2523                         //console.log('this>>>>>>>>>>>>>>>>>>>>>>',this);
2524                         if(flow==='savedQuery'){                                
2525                                 //reformed the DSL Object with Filter Entries and Template Entries
2526                                 this.formTemplateFilterValues(newDslObject['values'],newDslObject['nodeName'],key,idx);
2527                                 let entries=[];
2528                                 if(newCustomQuery[key]['templateEntries']){
2529                                         entries=newCustomQuery[key]['templateEntries'];
2530                                 }else{
2531                                         entries='';
2532                                 }
2533                                 filterValues=(newDslObject['values']) ? this.replaceFilterValues(newDslObject['values'],entries) :'';
2534                         }else{
2535                                 filterValues=(newDslObject['values'])? this.formFilterValues(newDslObject['values']):'';
2536                         }
2537                         query+=newDslObject['nodeName'];
2538                         if(newDslObject['props']){
2539                                 query+=newDslObject['props'];
2540                         }
2541                         if(newDslObject['values']){
2542                                 query+=filterValues;                    
2543                         }
2544                         tempDslQueryArr[count]=tempDslQueryArr[count]+query;
2545                         count++;
2546                 }
2547         });
2548         query=tempDslQueryArr.join('');
2549         return query;
2550  }
2551  contructDslNodes=(dsl,type,groupStart,groupEnd,edgeStart,edgeEnd)=>{       
2552         console.log(type+'contructDslNodes>>>>>>>>>>>>>>',dsl); 
2553         dsl=dsl.replace(/\s*\,\s*/g, ',')
2554         var declareEdgePattern=/\(\>(?:[^)(]+|\((?:[^)(]+|\([^)(]*\))*\))*\)|\!\(\>(?:[^)(]+|\((?:[^)(]+|\([^)(]*\))*\))*\)/g;
2555         let localEdges=dsl.match(declareEdgePattern);
2556         let edgesDsl=dsl;
2557         if(localEdges){
2558                 this.edgesArray=localEdges.concat(this.edgesArray);
2559                 edgesDsl=dsl.replace(declareEdgePattern,'>@$');
2560                 edgesDsl=edgesDsl.replace(/\!\>\@\$/g,'>!@$');  
2561         }       
2562         //capturing relations group b/w [] Parent only 
2563         let relations=this.capturingGroups(edgesDsl);           
2564         if(relations){
2565                 this.relationsArray=relations.concat(this.relationsArray);
2566                 for(var z in relations){
2567                         edgesDsl=edgesDsl.replace(relations[z],'#$');                           
2568                 }                       
2569         }
2570         //console.log('edgesDsl to padd getDslNodes>>>>>',edgesDsl);
2571         this.getDslNodes(edgesDsl,type,groupStart,groupEnd,edgeStart,edgeEnd);
2572 }
2573         
2574  getDslNodes=(dsl,type,groupStart,groupEnd,edgeStart,edgeEnd)=>{
2575         console.log('getDslNodes>>>>',dsl);
2576         let dslArray=[];
2577         let localDslNodes='';
2578         let relations=false;
2579         let edges=false;
2580         let traversal=false;
2581         dslArray = dsl.split('>');
2582         if(type === 'relationalNode'){
2583                 traversal=(dsl.indexOf('#$') === -1 && dslArray.length>1 && dsl.indexOf('@$') === -1);
2584         }
2585         for(var i=0;i<dslArray.length;i++){
2586                 if(dslArray[i] !== ''){
2587                         if(dslArray[i] === '#$'){//RelationalNode
2588                                 //relations to be enables
2589                                 localDslNodes=this.relationsArray[0];
2590                                 console.log(dslArray[i]+'<<<dslArray[i] localDslNodes>>>>>>>****>>>>',localDslNodes);
2591                                 localDslNodes=this.stripLastCharacter(this.stripFirstCharacter(localDslNodes));
2592                                 type='relationalNode';
2593                                 this.relationsArray=this.relationsArray.slice(1,this.relationsArray.length);                                    
2594                                 this.getDslRelationalNodes(localDslNodes,type);
2595                         }else if(dslArray[i].trim() === '@$' || dslArray[i].trim() === '!@$'){//EdgeNode
2596                         //edges should be enable
2597                                 localDslNodes=this.edgesArray[0];
2598                                 type='edgeNode'
2599                                 localDslNodes=this.stripLastCharacter(localDslNodes);
2600                                 if(localDslNodes.startsWith('!')){
2601                                         localDslNodes=localDslNodes.substr(3);
2602                                         type='negEdgeNode';
2603                                 }else{
2604                                         localDslNodes=localDslNodes.substr(2);
2605                                         type='edgeNode';
2606                                 }
2607                                 this.edgesArray=this.edgesArray.slice(1,this.edgesArray.length);
2608                                 this.getDslEdgeNodes(localDslNodes,type);
2609                         }
2610                         //node,traversal,relationalEdges
2611                         let x=i+1;                              
2612                         if(dslArray[x] && dslArray[x] === '#$'){
2613                                 relations=true;
2614                         }
2615                         if(dslArray[x] && dslArray[x] === '@$'){
2616                                 edges=true;
2617                         }                               
2618                         let tStart=(parseInt(i) === 0 && traversal)?true:false;
2619                         let tEnd=(parseInt(i) === dslArray.length-1 && traversal)?true:false;
2620                         if(i === dslArray.length-1){
2621                                 if(type==='edgeNode' || type === 'negEdgeNode'){
2622                                         edgeEnd=true;
2623                                         edgeStart=(dslArray.length===1)?true:false;
2624                                         groupStart=false;
2625                                         groupEnd=false;
2626                                 }else if(type==='relationalNode'){
2627                                         edgeEnd=false;
2628                                         edgeStart=false;                                                        
2629                                 }else{
2630                                         groupStart=false;
2631                                         groupEnd=false;
2632                                         edgeEnd=false;
2633                                         edgeStart=false;
2634                                 }
2635                         }
2636                         if(!(dslArray[i] === '#$' || dslArray[i].trim() === '@$' || dslArray[i].trim() === '!@$')){                                     
2637                                 dslArray[i]=dslArray[i].replace(/\,$/g,'').replace(/\]$/g,'').replace(/\>$/g,'').trim();
2638                                 this.formDslObject(dslArray[i],type,groupStart,groupEnd,relations,traversal,tStart,tEnd,edges,edgeStart,edgeEnd);
2639                         }                               
2640                 }                       
2641         }
2642         console.log('<<formDslObject>>>>>',JSON.stringify(this.dslObject));
2643 }
2644 getDslEdgeNodes=(edgesDsl,type)=>{              
2645         //space for future changes
2646         this.contructDslNodes(edgesDsl,type,false,false,true,false);
2647 }
2648 getDslRelationalNodes=(relationDsl,type)=>{
2649         console.log('getDslRelationalNodes>>>>>>>>>>>>',relationDsl)
2650         //var dslRelationNodes=relationDsl.substring(relationDsl.indexOf('['),relationDsl.lastIndexOf(']')+1);
2651         let dslRelationNodes=this.capturingGroups(relationDsl);
2652         let dslRelations= relationDsl;
2653         if(dslRelationNodes){
2654                 for(var z in dslRelationNodes){
2655                         dslRelations=dslRelations.replace(dslRelationNodes[z],'#$');
2656                 }
2657                 this.relationsArray=dslRelationNodes.concat(this.relationsArray);
2658         }
2659         let relationsList=dslRelations.replace(/\((?:[^)(]+|\((?:[^)(]+)\))*\)/g,'').replace(/\{(.*?)\}/g,'').trim('').replace(/\>\#\$/g,'').replace(/\>\@\$/g,'').replace(/\>\!\@\$/g,'').replace(/\!/g,'').split(',');
2660         dslRelations=','+dslRelations+'&&';
2661         let groupStart=false;
2662         let groupEnd=false;             
2663         //relationsList: have all Relations like node [node1>#$,node2,node3>node4]: possible to contain EdgeNodes,Traversal condition and inner relationNodes
2664         for(var k in relationsList){
2665                 console.log(k+'relationsList>>>>**',relationsList);
2666                 if(parseInt(k)===0){
2667                         groupStart=true;
2668                         groupEnd=false;
2669                 }else if(parseInt(k) === relationsList.length-1){
2670                         groupStart=false;
2671                         groupEnd=true;
2672                 }else{
2673                         groupStart=false;
2674                         groupEnd=false;
2675                 }
2676                 if(relationsList.length === 1){
2677                         groupStart=true;
2678                         groupEnd=true;
2679                 }
2680                 var relationPattern='';
2681                 
2682                 console.log('dslRelations>>>>>>>>>>>>',dslRelations);
2683                 let pattern=relationsList[k]+"(.*?)>\\#\\$(?=\\,|\\&&)|"+relationsList[k]+"(.*?)>\\@\\$(?=\\,|\\&&)|"+relationsList[k]+"(.*?)>\\!\\@\\$(?=\\,|\\&&)";
2684                 console.log('pattern>>>>>',pattern);
2685                 let relationP1 = new RegExp(pattern, 'g');                                      
2686                 let findDslRelation=dslRelations.match(relationP1);
2687                 console.log('findDslRelation>>>>>>',findDslRelation);
2688                 if(findDslRelation){//dslRelations.indexOf(relationsList[k]+'>#') !==-1 || dslRelations.indexOf(relationsList[k]+'>@$') !==-1){
2689                         relationPattern="(?:[^-]"+relationsList[k].split('>')[0]+"(.*?)(?=\,[a-z]|&&))|"+"(?:[^-]"+relationsList[k].split('>')[0]+"(?=\,[a-z]|&&))";
2690                 }else if(dslRelations.indexOf(relationsList[k]+',#') !== -1){
2691                         relationPattern="(?:[^-]"+relationsList[k]+"(.*?)(?=\,#))|"+"(?:[^-]"+relationsList[k]+"(?=\,#))";
2692                 }else if(relationsList[k] !== '#$'){
2693                         relationPattern="(?:[^-|^>]"+relationsList[k]+"(.*?)(?=\,[a-z]|>|&&))|"+"(?:[^-|^>]"+relationsList[k]+"(?=\,[a-z]|>|&&))";
2694                 }
2695                 if(relationsList[k] !== '#$'){          
2696                         console.log(k+'for relationPattern>>>',relationPattern);
2697                         console.log(k+'for dslRelations>>>>',dslRelations);
2698                         let relationPatternExp = new RegExp(relationPattern, 'g');                                      
2699                         let dslRelationArray=dslRelations.match(relationPatternExp);
2700                         console.log(k+'for dslRelationArray>>>>',dslRelationArray);
2701                         if(dslRelationArray){
2702                                 for(var j in dslRelationArray){ 
2703                                         console.log('dslRelationArray[j]>>>',dslRelationArray[j]);                                              
2704                                         let dslRelationNode=null;                                       
2705                                         dslRelationArray[j]= dslRelationArray[j].substr(1);
2706                                         dslRelations=dslRelations.replace(dslRelationArray[j],'@');
2707                                         console.log('groupStart>>>>>>>>>>',groupStart);
2708                                         this.contructDslNodes(dslRelationArray[j],type,groupStart,groupEnd);                                            
2709                                 }
2710                         }else{                          
2711                                 var relationPatternArray=relationsList[k].split('>');
2712                                 relationPattern=''; 
2713                                 for(var x=0;x<relationPatternArray.length;x++){
2714                                         if(x === 0){
2715                                                 relationPattern=relationPatternArray[x]+'(.*?)';
2716                                         }else{
2717                                                 relationPattern=relationPattern+'>'+relationPatternArray[x]+'(.*?)';
2718                                                 if(x===relationPatternArray.length-1){
2719                                                         relationPattern=relationPattern+'(?=\,[a-z]|&&)';
2720                                                 }                                               
2721                                         }
2722                                 }
2723                                 console.log('relationPattern>>>>>>',relationPattern);
2724                                 relationPatternExp = new RegExp(relationPattern, 'g');
2725                                 dslRelationArray=dslRelations.match(relationPatternExp);
2726                                 if(dslRelationArray){
2727                                         dslRelations=dslRelations.replace(dslRelationArray[0],'@');
2728                                         console.log('dslRelationArray!!!!!!!!!!!!!>>>>>',dslRelationArray);
2729                                         this.contructDslNodes(dslRelationArray[0],type,groupStart,groupEnd);
2730                                 }                               
2731                         }                       
2732                 }else{
2733                         let localDslNodes=this.relationsArray[0];
2734                         relationsList[k]=this.stripLastCharacter(this.stripFirstCharacter(localDslNodes));
2735                         this.relationsArray=this.relationsArray.slice(1,this.relationsArray.length);
2736                         console.log('relationsList[k]>***>>>',relationsList[k]);
2737                         //dslRelations=dslRelations.replace(dslRelationArray[j],'@');
2738                         this.contructDslNodes(relationsList[k],type,groupStart,groupEnd);
2739                         
2740                 }                               
2741         }
2742 }
2743 formDslObject=(dslArray,type,groupStart,groupEnd,relationState,traversal,tStart,tEnd,edges,eStart,eEnd,id)=>{
2744         let nodeType=dslArray.replace(/\((?:[^)(]+|\((?:[^)(]+)\))*\)/g,'').replace(/\{(.*?)\}/g,'').replace(/\!/g,'').trim('');
2745         let props=dslArray.match(/\{(.*?)\}/g);
2746         let propValues=dslArray.match(/\((?:[^)(]+|\((?:[^)(]+)\))*\)|\!\((?:[^)(]+|\((?:[^)(]+)\))*\)/g);
2747         var entries=[]
2748         var entry = {};
2749         entry.type = type;
2750         entry.relationsStart = groupStart;
2751         entry.relationsEnd= groupEnd;
2752         entry.relations=relationState;
2753         entry.nodeName = nodeType;
2754         entry.props=props;
2755         entry.traversal=traversal;
2756         entry.traversalStart=tStart;
2757         entry.traversalEnd=tEnd;
2758         entry.edgeEnable=(edges)?edges:false;
2759         entry.edgeStart=(eStart)?eStart:false;
2760         entry.edgeEnd=(eEnd)?eEnd:false;
2761         entry.values=propValues;
2762         entries.push(entry);
2763         let entityId=nodeType.replace(/\*/g,'');
2764         if(!this.nodeTypeArray.includes(entityId)){
2765                 this.nodeTypeArray.push(entityId);
2766                 this.dslObject[entityId] = entries;
2767         }else{
2768                 let newNodeType='';
2769                 let repeatMode=true;
2770                 for(var n=1;n<=this.nodeTypeArray.length;n++){
2771                         if(!this.nodeTypeArray.includes(entityId+'-'+n) && repeatMode){
2772                                 newNodeType=entityId+'-'+n;     
2773                                 repeatMode=false;
2774                         }
2775                 }
2776                 this.nodeTypeArray.push(newNodeType);
2777                 this.dslObject[newNodeType] = entries;
2778         }               
2779         console.log('nodeTypeArray>>>>',this.nodeTypeArray);
2780         console.log('this.dslObject>>>>',this.dslObject);       
2781 }
2782 formFilterValues=(propValues)=>{
2783         let templateQuery='';
2784         let negQuery='';        
2785         for(var k = 0; k < propValues.length; k++){
2786                 if(propValues[k].indexOf('!') !== -1){
2787                         negQuery += propValues[k];
2788                 }else{
2789                         templateQuery += propValues[k];
2790                 }               
2791         }
2792         if(negQuery!==''){
2793                 templateQuery+=negQuery;
2794         }
2795         console.log('templateQuery>>>>>>>>>>>>',templateQuery);
2796         return templateQuery;
2797 }
2798 replaceFilterValues=(propValues,entries)=>{
2799         console.log(propValues+'<<<propValues>>>>>',entries);
2800         let templateQuery='';
2801         let negQuery='';
2802         let count=1;
2803         for(var k = 0; k < propValues.length; k++){
2804                 let templatekey=(entries)?entries[k].templateKey+1:count;
2805                 if(propValues[k].indexOf('!') !== -1){
2806                         negQuery += "!($" + templatekey + ")";
2807                 }else{
2808                         templateQuery += "($" + templatekey + ")";
2809                 }       
2810                 count++;        
2811         }
2812         if(negQuery!==''){
2813                 templateQuery+=negQuery;
2814         }
2815         console.log('templateQuery>>>>>>>>>>>>',templateQuery);
2816         return templateQuery;
2817 }
2818 formTemplateFilterValues=(propvalues,nodeName,nodeId,idx)=>{
2819         let filterTemplateHeader = {};
2820         let filterEntries=[];
2821         var spaceRemoverPattern=/\,\s/g;
2822         var errorOccurred = false;
2823         var filterTypeDisplayArray = this.state.filterTypeDisplayList;
2824         let filterTypeDisplay= {'default':'Filter Type'};
2825         if(!filterTypeDisplayArray[idx] || filterTypeDisplayArray[idx] === undefined){
2826                 filterTypeDisplayArray.push(filterTypeDisplay);
2827         }
2828         var entries = [];
2829         var filterTypeEntries =[];
2830         var selectedProp=[];
2831         if(propvalues){
2832                 for(var i = 0; i < propvalues.length; i++){
2833                         console.log('propvalues['+i+']>>>>',propvalues[i]);
2834                         var entry = {};
2835                         let propVal = '';
2836                         if(propvalues[i].indexOf('!') !==-1){
2837                                 propVal=this.stripLastCharacter(this.stripFirstTwoCharacter(propvalues[i].trim()));
2838                         }else{
2839                                 propVal=this.stripLastCharacter(this.stripFirstCharacter(propvalues[i].trim()));
2840                         }                               
2841                         propVal = propVal.replace(spaceRemoverPattern,',');
2842                         //console.log('propVal>>>>>>>>>>>',propVal);                    
2843                         var matchesList = propVal.split(/',|\),/g)
2844                         //console.log('matchesList>>>>',matchesList);                                                                   
2845                         let type='';
2846                         let value='';
2847                         let errorFound=true;
2848                         let entryState=true;
2849                         for(var n=0;n<matchesList.length;n++){
2850                                 let scenario=true;
2851                                 let found=true;
2852                                 if(n==0){
2853                                         entry.name = this.stripFirstCharacter(matchesList[n].trim());
2854                                         selectedProp.push(this.stripFirstCharacter(matchesList[n].trim()));
2855                                 }else{
2856                                         let obj={};
2857                                         var lastChar=matchesList[n].charAt(matchesList[n].length-1);                                                    
2858                                         for(var x in filterTypeList){
2859                                                 if(found){
2860                                                         let pattern= new RegExp('^'+filterTypeList[x]+'\\((.*?)', 'g'); 
2861                                                         var filterExist=matchesList[n].match(pattern);
2862                                                         //console.log(matchesList[n]+'filterExist>>>>>',filterExist);
2863                                                         if(filterExist){
2864                                                                 var nodevalue='';
2865                                                                 if(lastChar===')'){
2866                                                                         nodevalue=matchesList[n].replace(filterTypeList[x],'').replace(/\(\'/,'').replace(/\'\)/,'');
2867                                                                 }else{
2868                                                                         nodevalue=this.stripLastCharacter(matchesList[n].replace(filterTypeList[x],'').replace(/\(\'/,''));
2869                                                                 }
2870                                                                 //console.log('before srtip>>>',nodevalue);                                     
2871                                                                 type=(type==='')?filterTypeList[x]:type+'^'+filterTypeList[x];
2872                                                                 value=(value==='')?nodevalue:value+'^'+nodevalue;
2873                                                                 scenario=false;
2874                                                                 found=false;
2875                                                                 errorFound=false;
2876                                                                 entryState=false;                                       
2877                                                                 obj[entry.templateKey+1] = filterTypeList[x];
2878                                                                 filterTypeEntries.push(obj);
2879                                                                 console.log('filterTypeDisplayArray....>*',filterTypeEntries);                                  
2880                                                         }
2881                                                 }                       
2882                                                 console.log(found+'found>>>>>>>>>>>>',value);
2883                                         }
2884                                         if(scenario){
2885                                                 console.log('inside else');
2886                                                 type=(type==='')?'EQ':type+'^'+'EQ';                                            
2887                                                 let val=this.stripFirstCharacter(matchesList[n].trim());
2888                                                 if(lastChar == '\''){
2889                                                         val=this.stripLastCharacter(val);
2890                                                 }
2891                                                 value=(value==='')?val:value+'^'+val;
2892                                                 entryState=false;
2893                                                 found=false;
2894                                                 errorFound=false;
2895                                         }                       
2896                                 }
2897                         }
2898                         if(!entryState){
2899                                 entry.type =type;
2900                                 entry.value =  value;
2901                                 entry.templateKey = i;
2902                                 entries.push(entry);            
2903                         }
2904                         if(errorFound && !errorOccurred){
2905                                 errorOccurred=true;
2906                         }
2907                 }                       
2908         }
2909         console.log('Initial Filtered Template Entries ' + JSON.stringify(entries));
2910         //nodeTypeOfDsl.push(nodeTypes[z]);
2911         let obj = {};
2912         obj[nodeId] = entries;
2913         filterTemplateHeader[nodeId]= {};
2914         filterTemplateHeader[nodeId]['enableAnd'] = true;
2915         filterTemplateHeader[nodeId]['propName'] = this.state.filterDisplay;
2916         filterTemplateHeader[nodeId]['selectedProp']=selectedProp;
2917         filterEntries.push(obj)
2918         filterTypeDisplayArray[idx][nodeId] = filterTypeEntries;
2919         let dslObject=this.dslObjectList[idx];
2920         if(dslObject){
2921                 dslObject[nodeId]['filterTemplateHeader']= filterTemplateHeader;
2922                 dslObject[nodeId]['filterEntries']=filterEntries;
2923                 dslObject[nodeId]['errorOccurred']=errorOccurred;
2924                 this.dslObjectList[idx]=dslObject;
2925         }else{
2926                 this.dslObject[nodeId]['filterTemplateHeader']= filterTemplateHeader;
2927                 this.dslObject[nodeId]['filterEntries']=filterEntries
2928                 this.dslObject[nodeId]['errorOccurred']=errorOccurred;
2929         }               
2930   }
2931   
2932   onAssociatedNodesCheckbox(e) {
2933       var cbValue = false;
2934       if (e.target.checked) {
2935         cbValue = true;
2936       }else {
2937         cbValue = false;
2938       }
2939       this.setState({ associatedNodesEnabled: cbValue });
2940   }
2941   onAggregateCheckbox(e) {
2942       var cbValue = false;
2943       if (e.target.checked) {
2944         cbValue = true;
2945         this.setState({associatedNodesEnabled: false});
2946       }else {
2947         cbValue = false;
2948       }
2949       this.setState({ isAggregateChecked: cbValue });
2950   }
2951   onPublicCheckbox(e) {
2952       var cbValue = false;
2953       if (e.target.checked) {
2954         cbValue = true;
2955         this.setState({ isPublicChecked: cbValue, isCommunitySharedChecked: false });
2956       }else {
2957         cbValue = false;
2958         this.setState({ isPublicChecked: cbValue });
2959       }
2960   }
2961   onMergedTabsCheckbox(e){
2962         var cbValue = false;
2963         if (e.target.checked) {
2964           cbValue = true;
2965           this.setState({ isMergedTabsChecked: cbValue});
2966         }else {
2967           cbValue = false;
2968           this.setState({ isMergedTabsChecked: cbValue });
2969         }
2970   }
2971   onGenerateEmailButton(){      
2972         let path='email-bulk-dsl-to-excel';
2973         this.generatebulkDslToExcel(path,true); 
2974   }
2975   onCommunitySharedCheckbox(e) {
2976       var cbValue = false;
2977       if (e.target.checked) {
2978         cbValue = true;
2979       }else {
2980         cbValue = false;
2981       }
2982       this.setState({ isCommunitySharedChecked: cbValue });
2983   }
2984   onDslConfigCheckbox(e, key) {
2985         var cbValue = false;
2986         var staticTemplateFilters = this.state.staticTemplateFilters;
2987         if (e.target.checked) {
2988           cbValue = true;
2989           staticTemplateFilters = staticTemplateFilters.filter(e => e !== key);
2990         }else {
2991           cbValue = false;
2992           staticTemplateFilters.push(key);
2993         }
2994         this.setState({ staticTemplateFilters: staticTemplateFilters });
2995     }
2996   handleOnFilter = (columnFilter,value) =>{
2997         console.log('handleOnFilter to Re-render', this.state.columnFilter);
2998         var applyState = true;
2999         if(value === ''){
3000                 for(var i= 0; i < columnFilter.length; i++){
3001                         var x = columnFilter[i];                
3002                         console.log('handleOnfilter ColumnFilterList.....',Object.keys(x));
3003                         Object.keys(x).forEach(function(key){
3004                                 if(x[key] !==''){
3005                                         applyState=false;
3006                                 }
3007                         });
3008                 }
3009         }else{
3010                 applyState = false;
3011         }
3012         
3013     this.setState({columnFilter : columnFilter,reRender:true,disableFilter: applyState});
3014   }
3015   
3016   alterDslQueryByRemoveSpaces = (dslQuery) =>{
3017             var p2='';
3018                 if((dslQuery.indexOf('(>') !==-1) || (dslQuery.indexOf('!(>') !==-1)){
3019                         p2=/\((?:[^>)(]|\((?:[^)(]+)\))*\)/g;
3020                 }
3021                 else{
3022                         p2 = /\((?:[^)(]+|\((?:[^)(]+)\))*\)/g;
3023                 }
3024                 var prop = dslQuery.match(p2);
3025                 var spacepattern = /\s(?!(^)]*\()/g;            
3026                 var newDslQuery='';
3027                 if(prop && prop.length > 0){
3028                         var x = dslQuery.replace(p2,'{*$}');
3029                         var matchStr = x.replace(spacepattern,'');                      
3030                         var propArray=matchStr.split('{*$}');                   
3031                         for(var i in prop){
3032                                 newDslQuery=newDslQuery+propArray[i]+prop[i];
3033                         }
3034                         newDslQuery = newDslQuery + propArray[propArray.length-1];
3035                 }else{
3036                         newDslQuery = dslQuery.replace(spacepattern,'');
3037                 }
3038                 newDslQuery = newDslQuery.trim();
3039                 console.log('New DSl Query after alterDslQueryByRemoveSpaces>>>>>>',newDslQuery);
3040                 return newDslQuery;
3041   }
3042  
3043   isTableFilterForAggregation = (columnFilterList,columnsList) => {
3044         console.log('isTableFilterForAggregation:aggregateTableFilterColumns>>>>>>',this.state.aggregateTableFilterColumns);
3045         //console.log('isTableFilterForAggregation:columnFilterList>>>>>>>>',columnFilterList);
3046         var nodeTypeArray = [];
3047         var columnsList = {};
3048         var filterMessage = {};
3049         var j = 0;      
3050         for(var i= 0; i < columnFilterList.length; i++){
3051                 var x = columnFilterList[i];            
3052                 console.log('isTableFilterForAggregation:Aggregate columnFilterList.....',Object.keys(x));
3053                 var  propValue = '';
3054                 Object.keys(x).forEach((key)=>{
3055                         var grabNode = key.split("|");
3056                         let indx=false;
3057                         let index='';
3058                         if(nodeTypeArray.indexOf(grabNode[0]) === -1){
3059                                 nodeTypeArray.push(grabNode[0]);
3060                                 j = j + 1;
3061                                 indx=true;
3062                                 index=j-1;
3063                         }else{
3064                                 index=nodeTypeArray.indexOf(grabNode[0]);
3065                         }
3066                         
3067                         if(!columnsList[nodeTypeArray[index]]){
3068                                 columnsList[nodeTypeArray[index]] = [];
3069                         }
3070                         if(!filterMessage[nodeTypeArray[index]]){
3071                                 filterMessage[nodeTypeArray[index]]=[];
3072                         }
3073                         let col='';
3074                         if(this.tableFilterAliasColumns[grabNode[0]][0] && this.tableFilterAliasColumns[grabNode[0]][0][grabNode[1]]){
3075                                 col=this.tableFilterAliasColumns[grabNode[0]][0][grabNode[1]];
3076                         }else{
3077                                 col=grabNode[1];
3078                         }
3079                         if(columnsList[nodeTypeArray[index]].indexOf(col) === -1){
3080                                 columnsList[nodeTypeArray[index]].push(col);
3081                                 if(x[key] != ''){
3082                                         let filterMsg = '';
3083                                         if(this.state.enableRealTime){
3084                                                 filterMsg='(\''+col +'\'' + ',' + TABULAR_FILTER_TYPE+'(\'' + x[key]+ '\'))';
3085                                         }else{
3086                                                 filterMsg='(\''+col +'\'' + ',' + '\'' + x[key] + '\')';
3087                                         }       
3088                                         filterMessage[nodeTypeArray[j-1]].push(filterMsg);
3089                                 }
3090                         }
3091                         propValue=x[key];                       
3092                 });                                     
3093         }
3094         console.log('isTableFilterForAggregation:nodeTypeArray><><><>',nodeTypeArray);  
3095         console.log('isTableFilterForAggregation:columnsList<><><>',columnsList);
3096         console.log('isTableFilterForAggregation:filterMessage>>>>>>>>',filterMessage);
3097         let dslQuery = this.state.value;
3098         var limitPattern = /limit[\s]\d+|limit\d+/ig
3099         var limitkey = dslQuery.match(limitPattern);
3100         if(limitkey){
3101                 dslQuery = dslQuery.replace(limitkey[limitkey.length-1],'').trim();
3102         }
3103         dslQuery = this.alterDslQueryByRemoveSpaces(dslQuery);
3104         //New adding
3105         this.dslObject={};
3106         this.nodeTypeArray=[];
3107         //create placeholders for NodeTypes with Propand Propvalues
3108         this.tempDslQuery=this.formTempDslQuery(dslQuery);
3109         //Preparing Json Object to render into Placeholder              
3110         this.contructDslNodes(dslQuery,'node',false,false,false,false);
3111         console.log('dslQuerydsl>>>>>>>>>>>>>',dslQuery);               
3112         //adding        
3113         Object.keys(this.dslObject).map((nodekey)=>{            
3114                 let nodeNo=parseInt(nodekey.substr(nodekey.length-2,nodekey.length-1).replace(/\-/g,''));
3115                 console.log('nodeNo>>>>>>>>>>>>>>',nodeNo);
3116                 let keyact=isNaN(nodeNo);
3117                 let nodeType=nodekey;
3118                 let actKey=nodekey.split('-');
3119                 console.log(nodeType+'>>>>nodeType<<<<nodeType>>>>',actKey);
3120                 if(!keyact){
3121                         actKey.splice(actKey.length-1,1);
3122                         nodeType=actKey.join('-')+nodeNo;
3123                 }
3124                 if(!nodeTypeArray.includes(nodeType) && nodeTypeArray.includes(actKey.join('-'))){
3125                         nodeType=actKey.join('-');
3126                 }
3127                 console.log('nodeType>>>>>>>>>>',nodeType);
3128                 var columns = columnsList[nodeType];
3129                 var filterMsg= filterMessage[nodeType];
3130                 console.log('CustomDsl js filterMsg:',filterMsg);
3131                 if(nodeType && this.dslObject[nodekey][0]){
3132                         if(filterMsg && filterMsg.length>0){
3133                                 for(var i=0;i<filterMsg.length;i++){
3134                                         let values=this.dslObject[nodekey][0]['values'];
3135                                         let nonExist=true
3136                                         let columnCompare=filterMsg[i].split(',')[0];
3137                                         if(values && values.length>0){
3138                                                 for(var n=0;n<values.length;n++){
3139                                                         console.log('values[n].indexOf(columnCompare)>>>>',values[n].indexOf(columnCompare));
3140                                                         if(values[n].indexOf(columnCompare) !==-1 && values[n].indexOf('!'+columnCompare) ===-1){
3141                                                                 values[n]=filterMsg[i];
3142                                                                 nonExist=false;
3143                                                         }
3144                                                 }
3145                                                 if(nonExist){
3146                                                         this.dslObject[nodekey][0]['values'].push(filterMsg[i]);        
3147                                                 }else{
3148                                                         this.dslObject[nodekey][0]['values']=values;    
3149                                                 }
3150                                         }else{
3151                                                 this.dslObject[nodekey][0]['values']=[];
3152                                                 this.dslObject[nodekey][0]['values'].push(filterMsg[i]);
3153                                         }
3154                                 }
3155                         }
3156                 }
3157         });
3158         this.dslObjectList =[];
3159         this.dslObjectList.push(this.dslObject);
3160         //Query to replace placeholders with JSON Object values depends on Flow either SavedQuery or TableFilters       
3161         let newDslQuery=this.formTemplateQuery('tableFilter');
3162         newDslQuery=newDslQuery.replace(/\'(as)\'/g,'\' as \'').replace(/\(\'\s(as)\s\'\)/g,'(\'as\')');
3163         if(limitkey){
3164                 newDslQuery+=' '+limitkey[limitkey.length-1];
3165         }
3166         console.log('query>>>>>>>>>>>>>>>>>>>>>****',newDslQuery);
3167         this.setState({value : newDslQuery, viewName: "CellLayout", aggregateActivePage:1}, function () { this.formQueryString(false,false,false); }.bind(this));
3168         //End   
3169   }
3170
3171   isTableFilterApply = (columnFilterList,nodeTypeList,columnsList,aliasColumnList) => {
3172     console.log('CustomDSL js ....columnFilterList:',columnFilterList);
3173         console.log('CustomDSL js .... nodeTypeList:',nodeTypeList);
3174         var nodeTypeListArray = [];
3175         if(!Array.isArray(nodeTypeList)){
3176                 nodeTypeListArray.push(nodeTypeList);
3177                 nodeTypeList = nodeTypeListArray;
3178         }
3179         console.log('CustomDSL js .... nodeTypeList After set:',nodeTypeList);
3180         var dslQuery = this.state.value;
3181         var limitPattern = /limit[\s]\d+|limit\d+/ig
3182         var limitkey = dslQuery.match(limitPattern);
3183         if(limitkey){
3184                 dslQuery = dslQuery.replace(limitkey[limitkey.length-1],'').trim();
3185         }
3186         dslQuery = this.alterDslQueryByRemoveSpaces(dslQuery);
3187         //New adding
3188         this.dslObject={};
3189         this.nodeTypeArray=[];
3190         //create placeholders for NodeTypes with Propand Propvalues
3191         this.tempDslQuery=this.formTempDslQuery(dslQuery);
3192         //Preparinga Json Object to render into Placeholder             
3193         this.contructDslNodes(dslQuery,'node',false,false,false,false);
3194         console.log('dslQuerydsl>>>>>>>>>>>>>',dslQuery);               
3195         //adding        
3196         Object.keys(this.dslObject).map((nodekey)=>{
3197                 var nodeType=this.dslObject[nodekey][0]['nodeName'].replace(/\*/g,'');
3198                 console.log('nodeType>>>>>>>>>>',nodeType);
3199                 var columnFilter = (columnFilterList[nodeType])?columnFilterList[nodeType][0]:[];
3200                 var aliasColumnFilters = (aliasColumnList[nodeType])?aliasColumnList[nodeType][0]:[];
3201                 console.log('CustomDsl js columnFilter:',columnFilter);
3202                 var columns = columnsList[nodeType];
3203                 console.log('CustomDsl js Columns:',columns);
3204                 if(columns && columnFilter.length>0){
3205                         for(var i=0;i<columns.length;i++){
3206                                 console.log(columnFilter[i]+'<<<<<<columnFilter[i]columns[i].value>>>>',columns[i]);
3207                                 var colAliasFilter='';
3208                                 for(var z=0;z<aliasColumnFilters.length;z++){
3209                                         if(aliasColumnFilters[z][columns[i].value]){
3210                                                 colAliasFilter=aliasColumnFilters[z][columns[i].value];
3211                                         }                               
3212                                 }               
3213                                 var colFilterValue = columnFilter[i][columns[i].value];      
3214                                 if(colFilterValue != ""){        
3215                                         let filterMsg = '';
3216                                         let col=(colAliasFilter)?colAliasFilter:columns[i].value;
3217                                         if(this.state.enableRealTime){
3218                                                 filterMsg='(\''+col +'\'' + ',' + TABULAR_FILTER_TYPE+'(\'' + colFilterValue + '\'))';
3219                                         }else{
3220                                                 filterMsg='(\''+col +'\'' + ',' +'\'' + colFilterValue + '\')';
3221                                         }                               
3222                                         let values=this.dslObject[nodekey][0]['values'];
3223                                         let nonExist=true;
3224                                         if(values && values.length>0){
3225                                                 for(var n=0;n<values.length;n++){
3226                                                         if(values[n].indexOf('(\''+col+'\'') !==-1 && values[n].indexOf('!(\''+col+'\'') ===-1){
3227                                                                 values[n]=filterMsg;
3228                                                                 nonExist=false;
3229                                                         }
3230                                                 }
3231                                                 if(nonExist){
3232                                                         this.dslObject[nodekey][0]['values'].push(filterMsg);   
3233                                                 }else{
3234                                                         this.dslObject[nodekey][0]['values']=values;    
3235                                                 }
3236                                         }else{
3237                                                 this.dslObject[nodekey][0]['values']=[];
3238                                                 this.dslObject[nodekey][0]['values'].push(filterMsg);
3239                                         }
3240                                 }
3241                         }
3242                 }
3243         });
3244         //Query to replace placeholders with JSON Object values depends on Flow either SavedQuery or TableFilters       
3245         this.dslObjectList =[];
3246         this.dslObjectList.push(this.dslObject);
3247         let newDslQuery=this.formTemplateQuery('tableFilter');
3248         newDslQuery=newDslQuery.replace(/\'(as)\'/g,'\' as \'').replace(/\(\'\s(as)\s\'\)/g,'(\'as\')');
3249         if(limitkey){
3250                 newDslQuery+=' '+limitkey[limitkey.length-1];
3251         }
3252         console.log('query>>>>>>>>>>>>>>>>>>>>>****',newDslQuery);
3253         this.setState({value : newDslQuery, viewName: "CellLayout", activePage:1}, function () { this.formQueryString(false,false,false); }.bind(this));
3254         //End
3255   }
3256   
3257   onTargetMenuOfFilterTypes = (listName,id) => {
3258         console.log('onTargetMenuOfFilterTypes>>>>',listName);
3259         let idArray=id.split('#');
3260         let key=idArray[0];
3261         let templateKey=parseInt(idArray[1]);
3262         let filterTypeIndex = parseInt(idArray[2]);
3263         let idx= parseInt(idArray[3]);
3264         var filterTypeDisplayList = this.state.filterTypeDisplayList;   
3265         var filterTypeDisplayArray = filterTypeDisplayList[idx];
3266         Object.keys(filterTypeDisplayArray).map((entry) => {
3267                 if(entry === key){
3268                         console.log('filterTypeDisplayArray.entry....',filterTypeDisplayArray[entry]);
3269                         if(filterTypeDisplayArray[entry][templateKey]){
3270                                 filterTypeDisplayArray[key][templateKey] = listName;
3271                         }else{
3272                                 let obj={};
3273                                 obj[templateKey+1]=listName;
3274                                 filterTypeDisplayArray[key].push(obj);
3275                         }
3276                 }
3277         });     
3278         let filterTemplateEntriesList = this.state.filterTemplateEntriesList;
3279         var filterTemplateEntriesArray = filterTemplateEntriesList[idx];        
3280         Object.keys(filterTemplateEntriesArray).map((entry)=>{
3281                 if(filterTemplateEntriesArray[entry][key]){
3282                         Object.keys(filterTemplateEntriesArray[entry][key]).map((ind) =>{
3283                                 if(filterTemplateEntriesArray[entry][key][ind].templateKey === templateKey){
3284                                         let type=filterTemplateEntriesArray[entry][key][ind].type.split('^');
3285                                         if(type[filterTypeIndex]){
3286                                                 type[filterTypeIndex]=listName
3287                                         }else{
3288                                                 type.push(listName);
3289                                         }
3290                                         filterTemplateEntriesArray[entry][key][ind].type=type.join('^');
3291                                 }
3292                         })
3293                 }
3294         });
3295         console.log('onTargetMenuOfFilterTypes filterTemplateEntriesArray>>>',filterTemplateEntriesArray);
3296         filterTemplateEntriesList[idx]=filterTemplateEntriesArray;
3297         filterTypeDisplayList[idx]=filterTypeDisplayArray;
3298         this.setState({filterTypeDisplayList:filterTypeDisplayList,filterTemplateEntriesList:filterTemplateEntriesList});
3299   }
3300   filterTags = (type,templateKey,key,idx) =>{
3301         console.log(key+'<<<filterTags>>>>>*',type);
3302         let filterType = (type === '')? this.state.filterTypeDisplayList[idx]['default']:type;
3303         let filterTag = '';
3304         if(APERTURE_SERVICE && this.state.enableRealTime){
3305                 console.log(filterType+'before passing Filter>*',this.state);
3306                 let filterTypesArray=filterType.split('^');     
3307                 let filters = Object.keys(filterTypesArray).map((index)=>{
3308                                                 return  <div style={{margin:'0px 0px 0px 5px'}}>
3309                                                                         <label>
3310                                                                                 <FilterTypes param={this.state}
3311                                                                                                         selectedFilter={filterTypesArray[index]}
3312                                                                                                         id={key+'#'+templateKey+'#'+index+'#'+idx}
3313                                                                                                         onMenuSelect={this.onTargetMenuOfFilterTypes} />
3314                                                                         </label>
3315                                                                 </div>
3316                                                 });
3317                 filterTag=<td width='20%'>{filters}</td>;
3318         }
3319         return filterTag;
3320   }
3321   populateFilteredColumnOptions = (nodekey,indx) =>{
3322         let keyact=isNaN(parseInt(nodekey.substr(nodekey.length-2,nodekey.length-1)));
3323         let actColumns ='';
3324         if(keyact){
3325                 actColumns =this.populateColumnOptions(nodekey);//this.populateColumnOptions(key);
3326         }else{
3327                 let actKey=nodekey.split('-');
3328                 actKey.splice(actKey.length-1,1);
3329                 actColumns =this.populateColumnOptions(actKey.join('-'));
3330         }        
3331         let filterTemplateEntries=this.state.filterTemplateEntriesList[indx];
3332         let filterTemplateHeader=this.state.filterTemplateHeaderList[indx];
3333         let selectedColumns=[];
3334         Object.keys(filterTemplateEntries).map((index) => {
3335                 let filterTemplateEntry = filterTemplateEntries[index];
3336                 Object.keys(filterTemplateEntry).map((key) =>{
3337                         let filterTemplateEntryKey=filterTemplateEntry[key];
3338                         if(nodekey === key){
3339                                 Object.keys(filterTemplateEntryKey).sort().map((entryKey, entry) => {
3340                                         if(filterTemplateEntryKey[entryKey].name !==''){
3341                                                 let index=actColumns.indexOf(filterTemplateEntryKey[entryKey].name);
3342                                                 actColumns.splice(index,1);
3343                                                 selectedColumns.push(filterTemplateEntryKey[entryKey].name);                            
3344                                         }
3345                                 });
3346                                 filterTemplateHeader[key]['selectedProp']=selectedColumns;
3347                         }                       
3348                 });
3349         });
3350         return actColumns;
3351   };
3352   /**AND OR functionality */
3353   addAndTemplate = (key,idx) =>{
3354         console.log('addAndTemplate:key',key);
3355         let templateEntriesList = this.state.filterTemplateEntriesList;
3356         let filterTemplateHeaderList= this.state.filterTemplateHeaderList;
3357         let templateEntries = this.state.filterTemplateEntriesList[idx];
3358         let filterTemplateHeader= this.state.filterTemplateHeaderList[idx];
3359         Object.keys(templateEntries).map((index) =>{
3360                 Object.keys(templateEntries[index]).map((entryKey)=>{
3361                         if(entryKey === key){
3362                                 let length=templateEntries[index][entryKey].length;
3363                                 let tempKey = (length===0)?length:templateEntries[index][entryKey][length-1].templateKey+1;
3364                                 let obj ={}
3365                                 obj['name']='';
3366                                 obj['value']='';
3367                                 obj['type']=(this.state.enableRealTime)?'EQ':'';
3368                                 obj['templateKey']=tempKey;
3369                                 obj['addition']=true;
3370                                 templateEntries[index][entryKey].push(obj);
3371                                 //templateEntries[index][entryKey]['enableAnd']=false;
3372                                 filterTemplateHeader[key]['enableAnd'] = false;
3373                                 filterTemplateHeader[key]['propName'] = this.state.filterDisplay;
3374                         }
3375                 });
3376         });
3377         templateEntriesList[idx]=templateEntries;
3378         filterTemplateHeaderList[idx]=filterTemplateHeader;
3379         this.setState({filterTemplateHeaderList:filterTemplateHeaderList,filterTemplateEntriesList:templateEntriesList});
3380   }
3381   addOrTemplate = (key,name,templateKey,idx) =>{
3382         console.log('addOrTemplate: key',key);
3383         let templateEntriesList = this.state.filterTemplateEntriesList;
3384         let templateEntries = templateEntriesList[idx];
3385         Object.keys(templateEntries).map((index) =>{
3386                 Object.keys(templateEntries[index]).map((entryKey)=>{
3387                         let templateEntry=templateEntries[index][entryKey];
3388                         if(entryKey === key){
3389                                 Object.keys(templateEntry).map((entry)=>{
3390                                         if(templateEntry[entry].templateKey === templateKey){
3391                                                 let value = templateEntry[entry].value;
3392                                                 let type = templateEntry[entry].type;
3393                                                 templateEntry[entry].value=value+'^';
3394                                                 let fType=(this.state.enableRealTime)?'EQ':'';
3395                                                 templateEntry[entry].type=type+'^'+fType;
3396                                                 templateEntry[entry].name = name;
3397                                         }
3398                                 })
3399                         }
3400                 });
3401         });
3402         console.log('addOrTemplate templateEntries>>>>',templateEntries);
3403         templateEntriesList[idx]=templateEntries;
3404         this.setState({filterTemplateEntriesList:templateEntriesList});
3405   }
3406   deleteOrTemplate = (key,templatekey,id,idx) =>{
3407         console.log('deleteOrTemplate');
3408         let templateEntriesList = this.state.filterTemplateEntriesList;
3409         let templateEntries = templateEntriesList[idx];
3410         let delIndx=parseInt(id.split('-')[1]);
3411         Object.keys(templateEntries).map((index) =>{
3412                 if(templateEntries[index][key]){
3413                         Object.keys(templateEntries[index][key]).map((i)=>{
3414                                 if(templateEntries[index][key][i].templateKey===templatekey){
3415                                         let valueArray = templateEntries[index][key][i].value.split('^');
3416                                         let typeArray = templateEntries[index][key][i].type.split('^');
3417                                         valueArray.splice(delIndx,1);
3418                                         typeArray.splice(delIndx,1)
3419                                         console.log('valueArray>>>>>>',valueArray);
3420                                         templateEntries[index][key][i].value=valueArray.join('^');
3421                                         templateEntries[index][key][i].type=typeArray.join('^');
3422                                 }
3423                         })                      
3424                 }               
3425         });
3426         console.log('deleteOrTemplate templateEntries>>>>',templateEntries);
3427         templateEntriesList[idx]=templateEntries;
3428         this.setState({filterTemplateEntriesList:templateEntriesList});
3429   }
3430   updatePropertyFilter = (listName,idkey) =>{
3431         console.log('updatePropertyFilter:',listName)
3432         let keys=idkey.split('#');
3433         let key=keys[0];
3434         let idx=parseInt(keys[2]);
3435         let templateKey=parseInt(keys[1]);
3436         let filterTemplateHeaderList = this.state.filterTemplateHeaderList;
3437         let filterTemplateHeader= filterTemplateHeaderList[idx];
3438         var filterTemplateEntriesList = this.state.filterTemplateEntriesList;
3439         var filterMap = filterTemplateEntriesList[idx];   
3440         filterTemplateHeader[key]['propName']=listName;
3441         //this.setState({filterTemplateHeader:filterTemplateHeader});   
3442         let status=false;
3443         Object.keys(filterMap).forEach((index) =>{
3444                 if(filterMap[index][key]){
3445                         Object.keys(filterMap[index][key]).forEach((i)=>{
3446                                 if(filterMap[index][key][i].templateKey === templateKey){
3447                                         if(filterMap[index][key][i].name === 'ERROR'){
3448                                                 filterMap[index][key][i].name= listName;                                                                        
3449                                                 let selectedProp=[];
3450                                                 console.log('filterTemplateHeader[key][selectedProp]>>>>',filterTemplateHeader[key]['selectedProp']);
3451                                                 if(filterTemplateHeader[key]['selectedProp']){
3452                                                         selectedProp=filterTemplateHeader[key]['selectedProp'];
3453                                                         let indSelect= selectedProp.indexOf(listName);
3454                                                         if(indSelect !== -1){
3455                                                                 selectedProp=selectedProp.splice(indSelect,1);
3456                                                                 filterTemplateHeader[key]['selectedProp']=selectedProp;
3457                                                         }                                       
3458                                                 }
3459                                                 filterTemplateHeader[key]['enableAnd'] = true;
3460                                                 console.log('ERRROOR CONDITION HANDLING!!!!');
3461                                                 this.templateErrorList[idx].pop();
3462                                                 this.updateSavedQueryTemplate('add',key,templateKey,filterMap,filterTemplateHeader,idx);
3463                                         }else{
3464                                                 console.log('Regular Scenario>>>>>');
3465                                                 filterTemplateHeaderList[idx]=filterTemplateHeader;
3466                                                 this.setState({filterTemplateHeaderList:filterTemplateHeaderList});
3467                                         }
3468                                 }
3469                         })
3470                 }
3471         });
3472   };
3473   /** */
3474   prepareDownloadRangeModel = () =>{
3475         let downloadExcelsFunc= this.getAllExcels;
3476         if(this.state.isAggregate){
3477                 downloadExcelsFunc=this.downloadAllAggregate;
3478         }
3479     let downloadRangeModel = (this.state.showDownloadResultsModal)? <DownloadRangeModel 
3480               showDownloadResultsModal={this.state.showDownloadResultsModal}
3481               totalPages={this.state.totalPages}
3482               totalResults={this.state.totalResults}
3483               triggerDownload={downloadExcelsFunc}
3484               errorDownloadResults={this.state.errorDownloadResults}
3485               downloadErrorMsg={this.state.downloadErrorMsg}
3486               triggerClose={this.closeDownloadResults}
3487               enableModelBusyFeedback={this.state.enableModelBusyFeedback}
3488           /> : '';
3489     return downloadRangeModel;
3490   }
3491   toggleRealTimeAnalysisCallback=(checked)=>{
3492         console.log('toggleRealTimeAnalysisCallback>>>>',checked);
3493         sessionStorage.setItem(ENVIRONMENT + 'ENABLE_ANALYSIS', !checked);      
3494         TABULAR_FILTER_TYPE=(APERTURE_SERVICE && !checked)?'CONTAINS':'=';
3495         this.baseState.enableRealTime=!checked;
3496         this.baseState.header='';       
3497         this.baseState.templateQuery='';
3498         this.baseState.filterTemplateEntries=[];
3499         this.baseState.filterTemplateHeader=[];
3500         this.baseState.filterTemplateError=false;
3501         this.baseState.nodeTypeOfDslTemplate=[];
3502         this.baseState.filterTemplateEntriesList=[];
3503         this.baseState.filterTemplateHeaderList=[];
3504         this.baseState.filterTemplateErrorList=[];
3505         this.baseState.nodeTypeOfDslTemplateList=[];
3506         this.baseState.templateQueryList=[];
3507         this.baseState.valueList=[];
3508         this.dslObject={};
3509         this.nodeTypeArray=[];
3510         this.dslObjectList=[];
3511         this.nodeTypeArrayList=[];
3512         this.edgesArray=[];
3513         this.relationsArray=[];
3514         this.tempDslQuery='';
3515         this.tempDslQueryList=[];
3516         this.templateError=[];
3517         this.templateErrorList={};
3518         this.setState({...this.baseState},()=>{this.buildDynamicByoq();});      
3519   }
3520   templateheaderSaveQuery = (id)=>{
3521         console.log('templateheaderSaveQuery>>>>>>>>>>>>>',id);
3522         let templateSavedQuery = '';
3523         let entityKeyAddition = 1;
3524         let templateheaderSaveQuery = '';
3525         let filterTemplateHeaderList = this.state.filterTemplateHeaderList;
3526         //templateheaderSaveQuery=Object.keys(this.state.filterTemplateEntriesList).map((id)=>{
3527                 //let tempheaderSavedQuery=''
3528                 if(this.state.filterTemplateEntriesList[id].length > 0 && !this.state.filterTemplateErrorList[id]){
3529                                 let filterTemplateEntries=this.state.filterTemplateEntriesList[id];
3530                                 let staticTemplateFilters = this.state.staticTemplateFiltersList[id];
3531                                 templateheaderSaveQuery= <div>
3532                                 {Object.keys(filterTemplateEntries).map((index) => {
3533                                         let filterTemplateEntry = filterTemplateEntries[index];
3534                                         return Object.keys(filterTemplateEntry).map((key) =>{
3535                                                 let filterTemplateEntryKey=filterTemplateEntry[key];
3536                                                 let columns =this.populateFilteredColumnOptions(key,id);//this.populateColumnOptions(key);
3537                                                 return  <table className='table table-hover table-striped savedQueryTemplate' style={{margin:'0px',padding:'2px'}} id={'table_'+key}>
3538                                                                         <thead>
3539                                                                                 <tr>
3540                                                                                         <th colSpan='2'>{key.toUpperCase()}</th>
3541                                                                                         {this.state.enableRealTime && <th width='20%'></th>}
3542                                                                                         <th width={(this.state.enableRealTime)?'30%':'25%'}></th>
3543                                                                                         <th width={(this.state.enableRealTime)?'20%':'25%'}>
3544                                                                                                 <button id={key+'_addAND'} className='btn btn-secondary' disabled ={!filterTemplateHeaderList[id][key]['enableAnd']} type='button' onClick={e => {this.addAndTemplate(key,id)}}>Add Filter</button>
3545                                                                                         </th>
3546                                                                                 </tr>
3547                                                                         </thead>
3548                                                                         <tbody>
3549                                                                                 {Object.keys(filterTemplateEntryKey).sort().map((entryKey, entry) => {
3550                                                                                         entityKeyAddition = parseInt(entryKey) + 2;
3551                                                                                         let valueArray = filterTemplateEntryKey[entryKey].value.split('^');
3552                                                                                         console.log("Comparing Static Array: " + JSON.stringify(staticTemplateFilters) + " with " + key + "|" + filterTemplateHeaderList[id][key]['propName']);
3553                                                                                         if(staticTemplateFilters.indexOf(key + "|" + filterTemplateEntryKey[entryKey].name) === -1 ){
3554                                                                                             return(
3555                                                                                                 <tr>
3556                                                                                                         <td width={(this.state.enableRealTime)?'10%':'25%'}>
3557                                                                                                                 <label>{'$' + (filterTemplateEntryKey[entryKey].templateKey + 1)}</label>
3558                                                                                                         </td>
3559                                                                                                         <td width={(this.state.enableRealTime)?'20%':'25%'}>
3560                                                                                                                 {filterTemplateEntryKey[entryKey].name !== '' && filterTemplateEntryKey[entryKey].name !== 'ERROR' && <label>{filterTemplateEntryKey[entryKey].name}</label>}
3561                                                                                                                 {filterTemplateEntryKey[entryKey].name === '' && <SelectFilter param={this.state}
3562                                                                                                                         filterList={columns}
3563                                                                                                                         id={key+'#'+filterTemplateEntryKey[entryKey].templateKey+'#'+id}
3564                                                                                                                         selectedFilter={filterTemplateHeaderList[id][key]['propName']}
3565                                                                                                                         onMenuSelect={this.updatePropertyFilter}/>}
3566                                                                                                                 {filterTemplateEntryKey[entryKey].name === 'ERROR' && <div className='inputBoxError'><SelectFilter param={this.state}
3567                                                                                                                         filterList={columns}
3568                                                                                                                         id={key+'#'+filterTemplateEntryKey[entryKey].templateKey+'#'+id}
3569                                                                                                                         selectedFilter={this.state.filterDisplay}
3570                                                                                                                         onMenuSelect={this.updatePropertyFilter}/></div>}
3571                                                                                                         </td>
3572                                                                                                         {this.filterTags(filterTemplateEntryKey[entryKey].type,filterTemplateEntryKey[entryKey].templateKey,key,id)}
3573                                                                                                         <td width={(this.state.enableRealTime)?'30%':'25%'}>
3574                                                                                                                 {Object.keys(valueArray).map((indx) =>{
3575                                                                                                                                 return(
3576                                                                                                                                         <div style={{margin:'5px'}}>
3577                                                                                                                                                 {valueArray[indx] === '' && <input id={key+'_'+indx} onBlur={e => this.updateTemplateFilterValues(key,filterTemplateEntryKey[entryKey].templateKey,e.target.value,e.target.id,id)}/>}
3578                                                                                                                                                 {valueArray[indx] !== '' && <input id={key+'_'+valueArray[indx]+'_'+indx} value={valueArray[indx]} onChange={e => this.updateTemplateFilterValues(key,filterTemplateEntryKey[entryKey].templateKey,e.target.value,e.target.id,id)}/>}
3579                                                                                                                                                 {indx == 0 && <button className={(filterTemplateEntryKey[entryKey].name !== '')?'btn btn-primary':'btn btn-secondary'} style={{padding:'2px',margin:'0px 0px 7px 5px'}} disabled={filterTemplateEntryKey[entryKey].name === ''} type='button' onClick={e => {this.addOrTemplate(key,filterTemplateEntryKey[entryKey].name,filterTemplateEntryKey[entryKey].templateKey,id)}}>+</button>}
3580                                                                                                                                                 {indx>0 && <button style={{padding:'2px',margin:'0px 0px 7px 5px'}} id={'delete-'+indx} className='btn btn-danger' type='button' onClick={e => {this.deleteOrTemplate(key,filterTemplateEntryKey[entryKey].templateKey,e.target.id,id)}}>x</button> }
3581                                                                                                                                         </div>
3582                                                                                                                                 )
3583                                                                                                                 })}
3584                                                                                                         </td>
3585                                                                                                         <td width={(this.state.enableRealTime)?'20%':'25%'}>
3586                                                                                                                 {filterTemplateEntryKey[entryKey].addition &&<button id='deleteAnd' className='btn btn-secondary' type='button' onClick={e => {this.updateSavedQueryTemplate('delete',key,filterTemplateEntryKey[entryKey].templateKey,'','',id)}}>Delete</button>}
3587                                                                                                         </td>
3588                                                                                                 </tr>);
3589                                                                                         }else {
3590                                                                                             return;
3591                                                                                         }
3592                                                                                 })}
3593                                                                         </tbody>
3594                                                                 </table>                                                
3595                                                                 })
3596                                                 })}
3597                                                 </div>
3598                 }
3599                 return templateheaderSaveQuery;
3600   };
3601   downloadBulkDslToExcel = () =>{
3602         console.log('downloadBulkDslToExcel>>>>>>>>>>>');               
3603         let path='bulk-dsl-to-excel';
3604         this.generatebulkDslToExcel(path,false)
3605   }
3606   generatebulkDslToExcel = (path,state) =>{
3607         this.setState({isLoading: true});
3608         Object.keys(settings).forEach((key)=>{
3609                 if(key==='ISAPERTURE' || key==='ISTABULAR'){
3610                         delete settings[key];
3611                 }
3612         })
3613         let mergedTabs=this.state.isMergedTabsChecked;
3614         var payload =  {'headers':{
3615                 'X-DslApiVersion':'V2',
3616                 'use-aperture': this.state.enableRealTime,
3617                 'schema-version': INVLIST.VERSION,
3618                 'merge-tabs':mergedTabs,
3619                 'accept': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
3620                 },'dsls': []};
3621                 
3622         Object.keys(this.state.queryNameList).map((index)=>{
3623                 if(!this.state.filterTemplateErrorList[index]){
3624                         let query=this.formFinalTemplateQuery(index);           
3625                         let obj={
3626                                 "query-id": parseInt(index)+1, 
3627                                 "query-name": this.state.queryNameList[index], 
3628                                 "query-description": this.state.queryDescriptionList[index], 
3629                                 "is-aggregate": this.state.isAggregateCheckedList[index], 
3630                                 "dsl": query
3631                                 };
3632                         payload['dsls'].push(obj);
3633                 }
3634         });
3635         var email='';   
3636         if(state){
3637                 let userid = sessionStorage.getItem(ENVIRONMENT + 'userId');
3638                 if(userid ==='testuid'){// For testing Purpose
3639                         email='AAI-UI-DEV@list.att.com';
3640                 }else{
3641                         email=userid+EMAIL_EXT;
3642                 }               
3643                 payload['headers']['email'] = email;
3644         }
3645         console.dir('CustomDSL:payload:' + JSON.stringify(payload));
3646         commonApi(settings, path, 'POST', payload, '',GlobalExtConstants.OVERRIDE_DOMAIN, null, [{
3647                                                                                                                                 "name":"X-DslApiVersion",
3648                                                                                                                                 "value": "V2"},
3649                                                                                                                                 {
3650                                                                                                                                 "name":"use-aperture",
3651                                                                                                                                 "value": this.state.enableRealTime
3652                                                                                                                                 },
3653                                                                                                                                 {
3654                                                                                                                                 "name":"schema-version",
3655                                                                                                                                 "value":INVLIST.VERSION},
3656                                                                                                                                 {
3657                                                                                                                                 "name":"accept",
3658                                                                                                                                 "value":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
3659                                                                                                                                 },{
3660                                                                                                                                 "name":"encode-response",
3661                                                                                                                                 "value":true}
3662                                                                                                                         ])
3663         .then(res => {                  
3664                         let success =true;
3665                         let failures=[];
3666                         if(!state){
3667                                 if(res['headers']['failures']){
3668                                         failures=res['headers']['failures'].split(',');
3669                                         for (var i = 0; i < failures.length; i++) {
3670                                                 var a = failures[i].split('|');
3671                                                 a.splice(1, 1);
3672                                                 failures[i] = a.join();
3673                                         }
3674                                         success=false;
3675                                 }else{
3676                                         let filename='';
3677                                         if(res['headers']['content-disposition']){
3678                                                 filename=res['headers']['content-disposition'].split('=')[1];
3679                                         }else if(res['headers']['Content-Disposition']){
3680                                                 filename=res['headers']['content-disposition'].split('=')[1];
3681                                         }
3682                                         const blob = new Blob([this.s2ab(atob(res.data))],
3683                                         { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,'});
3684                                         const url = window.URL.createObjectURL(blob);
3685                                         const anchor = document.createElement('a');
3686                                         document.body.appendChild(anchor);
3687                                         anchor.href = url;
3688                                         anchor.download = filename;
3689                                         anchor.click();
3690                                         window.URL.revokeObjectURL(url);
3691                                 }
3692                                 this.setState({
3693                                         isLoading: false,
3694                                         downloadTemplateStatus:success,
3695                                         failedDownloadedTemplate:failures,
3696                                         failedDownloadedTemplateMsg:'',
3697                                         failedEmailTemplateMsg:'',
3698                                         emailTriggerMsg:''
3699                                 },()=>{GeneralCommonFunctions.scrollTo("downloadTemplateStatusAlert");});                                                       
3700                         }else{
3701                                 let emailTriggerMsg='';
3702                                 let failedEmailTriggerMsg='';
3703                                 success=false;
3704                                 failures=[];
3705                                 if(res.status === 202){
3706                                         emailTriggerMsg='The job has been successfully triggered. The results will be emailed to '+ email +' when finished.'
3707                                 }else{
3708                                         failedEmailTriggerMsg='Failed to Generate an Email for selected template queries';
3709                                 }
3710                                 this.setState({
3711                                         isLoading: false,
3712                                         downloadTemplateStatus:success,
3713                                         failedDownloadedTemplate:failures,
3714                                         failedDownloadedTemplateMsg:'',
3715                                         failedEmailTemplateMsg:failedEmailTriggerMsg,
3716                                         emailTriggerMsg:emailTriggerMsg
3717                                 },()=>{GeneralCommonFunctions.scrollTo("downloadTemplateStatusAlert");});
3718                         }                               
3719                 }).catch(error => {
3720                         console.log('Bulk download xls Catch the Error>>>>>',error.response);
3721                         let ErrorMessage=(state)?'Failed to Generate an Email for selected template queries':'Failed to Download selected template queries';
3722                         if (error.response && error.response.data) {
3723                                 if(error.response.data.status){
3724                                         ErrorMessage += " Code: " + error.response.data.status;
3725                                 }
3726                                 if(error.response.data.msg){
3727                                         ErrorMessage += " - " + JSON.stringify(error.response.data.msg);
3728                           }
3729                         }
3730                         if(state){
3731                                 this.setState({
3732                                         isLoading: false,
3733                                         downloadTemplateStatus:false,
3734                                         failedDownloadedTemplate:[],
3735                                         failedDownloadedTemplateMsg:'',
3736                                         failedEmailTemplateMsg:ErrorMessage
3737                                 },()=>{GeneralCommonFunctions.scrollTo("downloadTemplateStatusAlert");});
3738                         }else{
3739                                 this.setState({
3740                                         isLoading: false,
3741                                         downloadTemplateStatus:false,
3742                                         failedDownloadedTemplate:[],
3743                                         failedDownloadedTemplateMsg:ErrorMessage,
3744                                         failedEmailTemplateMsg:'',
3745                                         emailTriggerMsg:''
3746                                 },()=>{GeneralCommonFunctions.scrollTo("downloadTemplateStatusAlert");});
3747                         }
3748                         
3749                 });
3750   }
3751   s2ab=(s)=> {
3752         var buf = new ArrayBuffer(s.length);
3753         var view = new Uint8Array(buf);
3754         for (var i=0; i!=s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
3755         return buf;
3756   }
3757   templateList = () =>{
3758         var filterTypeHeader='';
3759         if(APERTURE_SERVICE){           
3760                 filterTypeHeader =  (this.state.enableRealTime)?<th scope='col' width='20%'>Filter Type</th>:''; 
3761         }
3762         var listOfTemplate=[];
3763         Object.keys(this.state.filterTemplateEntriesList).map((idx)=>{
3764                 let templateList =<div id={"template_"+idx} className="col-lg-10 templateview">
3765                                                 {this.state.filterTemplateEntriesList[idx].length > 0 && !this.state.filterTemplateErrorList[idx] &&
3766                                                         <div className='card d3-model-card model-card-content'>
3767                                                           <Alert id='saveSuccess' bsStyle='success' className={this.state.saveSuccessfulMsg && !this.state.isEditModal ? 'show' : 'hidden'} onDismiss={() => this.setState({saveSuccessfulMsg: false})}>
3768                                                                   <h3>Query Saved Successfully</h3>
3769                                                                   <p>
3770                                                                           {this.state.saveSuccessfulMsg}
3771                                                                   </p>
3772                                                         </Alert>
3773                                                         <div className='card-header'>
3774                                                                 <div>
3775                                                                         <h3><strong>{parseInt(idx)+1}.{this.state.queryNameList[idx]}</strong> - {this.state.queryDescriptionList[idx]}</h3>
3776                                                                 </div>
3777                                                         </div>
3778                                                         <div>
3779                                                                 <div className='card-header'>
3780                                                                         <h5>{this.state.templateQueryList[idx]}</h5>
3781                                                                 </div>
3782                                                                 <table className="table table-hover table-striped" style={{margin:'0px',padding:'2px'}}>
3783                                                                         <thead>
3784                                                                                 <tr>
3785                                                                                         <th scope="col" width={(this.state.enableRealTime)?'10%':'25%'}>Filter Key</th>
3786                                                                                         <th scope="col" width={(this.state.enableRealTime)?'20':'25%'}>Filter Name</th>
3787                                                                                         {filterTypeHeader}
3788                                                                                         <th scope="col" width={(this.state.enableRealTime)?'30%':'25%'}>Filter Value</th>
3789                                                                                         <th scope="col" width={(this.state.enableRealTime)?'20%':'25%'}> Action</th>
3790                                                                                 </tr>
3791                                                                         </thead>
3792                                                                 </table>
3793                                                         </div>
3794                                                         <div className='card-content model-card-content' style={{margin:'0px'}}>                                                                        
3795                                                                 {this.templateheaderSaveQuery(idx)}                               
3796                                                          </div>
3797                                                         <div className='card-footer'>
3798                                                                 <button id='runSavedQuery' className='btn btn-primary btn-space' type='button' onClick={e => {this.runTemplate(idx)}}>Run Query</button>
3799                                                                 <button id='manualEditQuery' className='btn btn-secondary btn-space' type='button' onClick={e =>{this.showEditDSLModal(idx)}} disabled={this.templateError.length>0}>Manual Edit & Run</button>
3800                                                                 <button id='saveQuery' className='btn btn-outline-secondary btn-space' type='button' onClick={e =>{this.saveTemplate(idx)}} disabled={this.templateError.length>0}>Save</button>
3801                                                                 <div className={'checkbox ' + (GlobalExtConstants.INVLIST.IS_ONAP ? 'hidden' : '' )}>
3802                                                                         <label>
3803                                                                         <input type="checkbox" id='aggregateObjects' checked={this.state.isAggregateCheckedList[idx]} onChange={this.onAggregateCheckbox.bind(this)} />
3804                                                                         Aggregate Objects
3805                                                                         </label>
3806                                                                 </div>
3807                                                         </div>
3808                                          </div>
3809                                 }
3810                                 {this.state.queryNameList[idx] && this.state.filterTemplateEntriesList[idx].length === 0 && !this.state.filterTemplateErrorList[idx] &&
3811                                         <div className='addPaddingTop alert alert-warning' role="alert">
3812                                           No filters present to populate for this saved query, please run as is or edit the query manually and run.
3813                                         </div>
3814                                 }
3815                                 {this.state.filterTemplateErrorList[idx] &&
3816                                   <div className='addPaddingTop alert alert-danger' role="alert">
3817                                         An error occurred in parsing the template, please try a different template or contact the data steward to resolve this issue.
3818                                   </div>
3819                                 }
3820                 </div>;
3821                 listOfTemplate.push(templateList);
3822         });     
3823         console.log('listOfTemplate>>>>>#####>>>>>>>',listOfTemplate);
3824         return listOfTemplate;
3825   }
3826
3827
3828   render(){
3829         let downloadRangeModel = this.prepareDownloadRangeModel();
3830         let templateList= this.templateList();
3831         var toggelRealtimeAnalysis = '';
3832         var emailCheckbox = <div className={(this.dslObjectList.length>0)?'show':'hidden'}>
3833                                                         <div className="checkbox">
3834                                                                 <OverlayTrigger  placement='top' overlay={<Tooltip id='tooltip-top'>{'Report will be generated and emailed to '+sessionStorage.getItem(ENVIRONMENT + 'userId')+'@att.com when finished'}</Tooltip>}>
3835                                                                         <span className="d-inline-block" style={{display: 'inline-block'}}>
3836                                                                                 <Button bsSize='small' disabled={(this.dslObjectList.length===0)} onClick={() => {this.onGenerateEmailButton()}}>
3837                                                                                         Generate & Email <i className='icon-documents-folder'></i>
3838                                                                                 </Button>
3839                                                                         </span>
3840                                                                 </OverlayTrigger>
3841                                                         </div>
3842                                                 </div>
3843         var mergedTabs = <div className={(this.dslObjectList.length>0)?'show':'hidden'}>
3844                                                 <div className="checkbox">
3845                                                         <label>
3846                                                                 <input type="checkbox" checked={this.state.isMergedTabsChecked} onChange={this.onMergedTabsCheckbox.bind(this)} />
3847                                                                 Merge Tabs
3848                                                         </label>
3849                                                 </div>
3850                                          </div>
3851         var downloadAllTemplateQueries = <div className={(this.dslObjectList.length>0)?'show':'hidden'}>
3852                                                                                 <OverlayTrigger  placement='top' overlay={<Tooltip id='tooltip-top'>{this.downloadBulkTooltip}</Tooltip>}>
3853                                                                                         <span className="d-inline-block" style={{display: 'inline-block'}}>
3854                                                                                                 <Button bsSize='small' disabled={(this.dslObjectList.length===0)} onClick={() => {this.downloadBulkDslToExcel()}}>
3855                                                                                                         Download Loaded Queries <i className='icon-documents-downloadablefile'></i>
3856                                                                                                 </Button>
3857                                                                                         </span>
3858                                                                                 </OverlayTrigger>                                                                               
3859                                                                         </div>
3860         let downloadTemplateStatusAlert= <div className={(this.dslObjectList.length>0)?'show':'hidden'}>
3861                                                                                 <Alert id="saveSuccess" bsStyle="success" className={(this.state.downloadTemplateStatus && this.state.failedDownloadedTemplate.length===0)?'show':'hide'} onDismiss={() => this.setState({
3862                                                                                                 downloadTemplateStatus:false,
3863                                                                                                 failedDownloadedTemplate:[],
3864                                                                                                 failedDownloadedTemplateMsg:'',
3865                                                                                                 failedEmailTemplateMsg:'',
3866                                                                                                 emailTriggerMsg:''})}>
3867                                                                                         <h3>Download Loaded Templates are  Successfully</h3>
3868                                                                                         <p>
3869                                                                                                 The selected templates downloaded successfull.
3870                                                                                         </p>
3871                                                                                 </Alert>
3872                                                                                 {this.state.failedDownloadedTemplate.length>0 && <Alert id="saveFailure" bsStyle="danger"  onDismiss={() => this.setState({
3873                                                                                                 downloadTemplateStatus:false,
3874                                                                                                 failedDownloadedTemplate:[],
3875                                                                                                 failedDownloadedTemplateMsg:'',
3876                                                                                                 failedEmailTemplateMsg:'',
3877                                                                                                 emailTriggerMsg:''})}>
3878                                                                                         <h3>Download Loaded Templates are Failed</h3>
3879                                                                                         <p>                                                                                     
3880                                                                                                 {this.state.failedDownloadedTemplate.toString()} templates are failed to download.Please refer the downloaded spreadsheet for more details.
3881                                                                                         </p>
3882                                                                                 </Alert>}
3883                                                                                 {this.state.failedDownloadedTemplateMsg !=='' && <Alert id="saveFailure" bsStyle="danger" onDismiss={() => this.setState({
3884                                                                                                 downloadTemplateStatus:false,
3885                                                                                                 failedDownloadedTemplate:[],
3886                                                                                                 failedDownloadedTemplateMsg:'',
3887                                                                                                 failedEmailTemplateMsg:'',
3888                                                                                                 emailTriggerMsg:''})}>
3889                                                                                         <h3>Download Loaded Templates are Failed</h3>
3890                                                                                         <p>                                                                                     
3891                                                                                                 {this.state.failedDownloadedTemplateMsg}
3892                                                                                         </p>
3893                                                                                 </Alert>}
3894                                                                                 {this.state.emailTriggerMsg !=='' && <Alert id="saveSuccess" bsStyle="success" onDismiss={() => this.setState({failedEmailTemplateMsg:'',emailTriggerMsg:''})}>
3895                                                                                         <h3>Generate & Email Triggered</h3>
3896                                                                                         <p>                                                                                     
3897                                                                                                 {this.state.emailTriggerMsg}
3898                                                                                         </p>
3899                                                                                 </Alert>}
3900                                                                                 {this.state.failedEmailTemplateMsg !=='' && <Alert id="saveFailure" bsStyle="danger" onDismiss={() => this.setState({failedEmailTemplateMsg:'',emailTriggerMsg:''})}>
3901                                                                                         <h3>Generate & Email Templates is Failed</h3>
3902                                                                                         <p>                                                                                     
3903                                                                                                 {this.state.failedEmailTemplateMsg}
3904                                                                                         </p>
3905                                                                                 </Alert>}                                                                               
3906                                                                         </div>
3907         if(APERTURE_SERVICE){           
3908                 toggelRealtimeAnalysis = <div className='toggleSwitch'><BootstrapSwitchButton
3909                                                                         checked={!this.state.enableRealTime}
3910                                                                         onlabel='Real Time'
3911                                                                         onstyle='danger'
3912                                                                         offlabel='Analysis'
3913                                                                         offstyle='success'
3914                                                                         style='w-100 mx-3'
3915                                                                         onChange={(checked) => {
3916                                                                                 this.toggleRealTimeAnalysisCallback(checked);
3917                                                                         }}
3918                                                                 /></div>             
3919         }
3920                 const inputProps = {
3921                         placeholder: 'Please enter a query',
3922                         value: this.state.value,
3923                         onChange: this.onChange,
3924                         onSelect: this.onSelect,
3925                         onClick: this.onClick
3926                 };
3927
3928                 let nodes = [];
3929                 if ( this.state.isAggregate && this.state.aggregateNodes.length > 0 ) {
3930
3931                         console.log('nodes exist', JSON.stringify(this.state.aggregateNodes[0]));
3932             if(this.state.isAggregate && this.state.viewName === 'CardLayout'){
3933                 var nodeDetails = this.state.aggregateNodes.map(entry => {
3934                                                            return <Col lg={4} md={4} sm={6} xs={12}>
3935                                                                    <div className='card aggregate-card'>
3936                                                                         <div className='card-header'>
3937                                                                           <h4 className='card-title'>{entry.nodePath}</h4>
3938                                                                         </div>
3939                                                                         <div className='card-content aggregate-card-content'>
3940                                                                         <span>
3941                                                                     {entry && typeof entry.map === 'function' && entry.map(subEntry =>
3942                                                                          {  let nodesPropList={};
3943                                                                                                                                                         return Object.keys(subEntry).map((node) => {
3944                                                                                                                                                                                  console.log("subentry : " + JSON.stringify(node + ' ' + JSON.stringify(subEntry[node])));
3945                                                                                                                                                                                  let description='';
3946                                                                                                                                                                                  let nodeType=subEntry[node]['node-type'];
3947                                                                                                                                                                                  if(!nodesPropList[nodeType]){                                                                                                                                                                                  
3948                                                                                                                                                                                         var requiredParams = buildAttrList(nodeType,[],'mandatory');
3949                                                                                                                                                                                         nodesPropList[nodeType]=requiredParams;
3950                                                                                                                                                                                  }
3951                                                                                          return (<span>
3952                                                                                                      {this.state.associatedNodesEnabled && (<Alert bsStyle="info"><strong>{node}</strong></Alert>)}
3953                                                                                                      {Object.keys(subEntry[node].properties).map((key)=>{
3954                                                                                                                                                                                                                  let propKey=key.split('|')[1];
3955                                                                                                                                                                                                                  let found=true;
3956                                                                                                                                                                                                                  for(var a in nodesPropList[nodeType]){
3957                                                                                                                                                                                                                         if(propKey===nodesPropList[nodeType][a].value){
3958                                                                                                                                                                                                                                 found=false;
3959                                                                                                                                                                                                                                 return (<p className="aggregate-attribute"><strong title={nodesPropList[nodeType][a].description}>{key}</strong> : {"" + subEntry[node].properties[key]}</p>);
3960                                                                                                                                                                                                                         }
3961                                                                                                                                                                                                                  }
3962                                                                                                                                                                                                                  if(found){
3963                                                                                                                                                                                                                         return (<p className="aggregate-attribute"><strong>{key}</strong> : {"" + subEntry[node].properties[key]}</p>);
3964                                                                                                                                                                                                                  }                                                                                                        
3965                                                                                                      })
3966                                                                                                      }
3967                                                                                                  </span>)
3968                                                                                      })
3969                                                                          })
3970                                                                      }
3971
3972                                                                           {this.state.associatedNodesEnabled && (<Alert bsStyle="info"><strong>{entry.fullPath}</strong></Alert>)}
3973                                                                         </span>
3974                                                                         </div>
3975                                                                     </div>
3976                                                                    </Col>;
3977                                                    });
3978                 nodes =
3979                 <div className='model-container'>
3980                         {nodeDetails}
3981                 </div>;
3982             }else if(this.state.isAggregate && this.state.viewName === 'CellLayout'){
3983                if(this.state.aggregateAttrList.length > 0 && this.state.aggregatePaths){
3984                    var types = this.state.aggregatePaths;
3985                    var type = types[0];
3986                    let tabs=types.map((nodeType,index) => {
3987                            if(this.state.tabularAggregateData[nodeType] && this.state.tabularAggregateColumns[nodeType]){
3988                              return(
3989                                <Tab eventKey={nodeType} title={nodeType}>
3990                                  <BootstrapTable
3991                                      id={nodeType}
3992                                      keyField='id'
3993                                      data={this.state.tabularAggregateData[nodeType]}
3994                                      columns={this.state.tabularAggregateColumns[nodeType]}
3995                                      bordered={ true }
3996                                      headerClasses='table-header-view'
3997                                      columnFilter={ true }
3998                                      filter={ filterFactory() }
3999                                      bootstrap4 striped hover condensed
4000                                  />
4001                                </Tab>
4002                              )
4003                            }
4004                    });
4005
4006                     nodes =
4007                          <div>
4008                                 <button type='button' className={(this.state.disableFilter)? 'btn btn-outline-secondary' : 'btn btn-primary'} disabled={this.state.disableFilter} onClick={() => {this.isTableFilterForAggregation(this.state.columnFilter,this.state.tabularAggregateColumns[type])}} style={{float: 'right', margin: '2px'}}>Apply Filters (All)</button>
4009                                 <Tabs defaultActiveKey={type} id="multipleTabularView">
4010                                         {tabs}
4011                                 </Tabs>
4012                          </div>;
4013                 }
4014             }else if(this.state.isAggregate && this.state.viewName === 'VisualLayout'){
4015                      nodes = <span></span>;
4016             }
4017                 }else if (this.state.nodes.length > 0){
4018                     const modelGalleryElement = <ModelGallery
4019                                                                         nodes={this.state.nodes}
4020                                                                         viewName={this.state.viewName}
4021                                                                         historyStackString={this.props.location.historyStackString}
4022                                                                         openHistoryModal={this.openHistory}
4023                                                                         isPageNumberChange={this.state.isPageNumberChange}
4024                                                                         resetColumnInd={this.state.resetColumnFilters}
4025                                                                         isTableFilterApply={this.isTableFilterApply}
4026                                                                         dslQuery={this.state.value}
4027                                                                         enableRealTime={this.state.enableRealTime}
4028                                                                         tableFilterAliasColumns={this.tableFilterAliasColumns}/>;
4029             nodes =
4030             <div className='model-container'>
4031                 {modelGalleryElement}
4032             </div>;
4033                 }                               
4034         return(
4035                 <div>
4036                         {toggelRealtimeAnalysis}
4037                         <div className='addPadding customDsl'>
4038                     <div className='static-modal'>
4039                                         <Modal show={this.state.showHistoryModal} onHide={this.closeHistory}>
4040                                                 <Modal.Header>
4041                                                         <Modal.Title>Retrieve {(this.state.focusedNodeType) ? this.state.focusedNodeType: ' BYOQ Query '} History</Modal.Title>
4042                                                 </Modal.Header>
4043                                                 <Modal.Body>
4044                                                         <form className={this.state.showModelOptions ? 'show' : 'hidden'} id='historyForm' name='historyForm'>
4045                                                                 <div className="radio">
4046                                                                         <label>
4047                                                                         <input type="radio" value="nodeState"
4048                                                                                                         checked={this.state.historyType === 'nodeState'}
4049                                                                                                         onChange={(e) => this.setHistoryType(e)} />
4050                                                                         View state at
4051                                                                         </label>
4052                                                                 </div>
4053                                                                 <div className="radio">
4054                                                                         <label>
4055                                                                         <input type="radio"  value="nodeLifeCycleSince"
4056                                                                                                         checked={this.state.historyType === 'nodeLifeCycleSince'}
4057                                                                                                         onChange={(e) => this.setHistoryType(e)} />
4058                                                                         View updates since
4059                                                                         </label>
4060                                                                 </div>
4061                                                                 <div className="radio">
4062                                                                         <label>
4063                                                                         <input type="radio" value="nodeLifeCycle"
4064                                                                                                         checked={this.state.historyType === 'nodeLifeCycle'}
4065                                                                                                         onChange={(e) => this.setHistoryType(e)} />
4066                                                                         View all updates
4067                                                                         </label>
4068                                                                 </div>
4069                                                         </form>
4070                                                         <div className={this.state.enableCalendar ? 'show' : 'hidden'}>
4071                                                                         <DatePicker
4072                                                                                         inline
4073                                                                                                         selected={this.state.startDate}
4074                                                                                                         onChange={(newDate) => this.handleDateChange(newDate)}
4075                                                                                                         showTimeSelect
4076                                                                                                         timeFormat="HH:mm"
4077                                                                                                         timeIntervals={15}
4078                                                                                                         dateFormat="MMMM D, YYYY h:mm a"
4079                                                                                                         timeCaption="time"
4080                                                                                         />
4081                                                                         </div>
4082                                                 </Modal.Body>
4083                                                 <Modal.Footer>
4084                                                         <Button onClick={this.closeHistory}>Close</Button>
4085                                                         <Button onClick={this.submitHistory}>Submit</Button>
4086                                                 </Modal.Footer>
4087                                         </Modal>
4088         </div>
4089         <div className='static-modal'>
4090                 <Modal show={this.state.showEditModal} onHide={this.closeEditDSLModal}>
4091                         <Modal.Header>
4092                                 <Modal.Title>Edit DSL Query</Modal.Title>
4093                         </Modal.Header>
4094                         <Modal.Body>
4095                     <form id='dslQueryEditable' name='dslQueryEditable'>
4096                         <FormGroup controlId="dslQuery">
4097                               <ControlLabel>DSL Query</ControlLabel>
4098                               <FormControl className="template-textarea" onChange={this.bindEdits.bind(this)} value={this.state.editModel} componentClass="textarea" placeholder="Enter DSL Query" />
4099                          </FormGroup>
4100                     </form>
4101                         </Modal.Body>
4102                         <Modal.Footer>
4103                                 <Button onClick={this.closeEditDSLModal}>Close</Button>
4104                                 <Button onClick={this.submitEditAndRunDSL}>Submit</Button>
4105                         </Modal.Footer>
4106                 </Modal>
4107         </div>
4108         <div className='static-modal'>
4109                                 <Modal show={this.state.showNodeModal} onHide={this.closeNodeModal} dialogClassName="modal-override">
4110                                         <Modal.Header>
4111                                                 <Modal.Title>Retrieve {this.state.nodeDisplay}</Modal.Title>
4112                                         </Modal.Header>
4113                                         <Modal.Body>
4114                                 <Grid fluid={true}>
4115                                       <Row className='show-grid'>
4116                                         <Col lg={12} md={12} sm={12} xs={12}>
4117                                             <ModelCard
4118                                                         key={this.state.focusedNode.id}
4119                                                         nodeId={this.state.focusedNode.id}
4120                                                         nodeType={this.state.focusedNode['node-type']}
4121                                                         nodeProps={this.state.focusedNode.properties}
4122                                                         nodeRelatives={this.state.focusedNode['related-to']}
4123                                                         nodeUrl={this.state.focusedNode.url}
4124                                                         historyStackString={this.props.location.historyStackString}
4125                                                         openHistoryModal={this.openHistory}
4126                                                                                                                 enableRealTime={this.state.enableRealTime}/>
4127                                         </Col>
4128                                       </Row>
4129                                 </Grid>
4130                                         </Modal.Body>
4131                                         <Modal.Footer>
4132                                                 <Button onClick={this.closeNodeModal}>Close</Button>
4133                                         </Modal.Footer>
4134                                 </Modal>
4135         </div>
4136         <div className='static-modal'>
4137                                 <Modal show={this.state.showSaveModal} onHide={this.closeSaveModal} dialogClassName="modal-override">
4138                                     <Spinner loading={this.state.enableSaveBusyFeedback}>
4139                                             <Modal.Header>
4140                                                 <Modal.Title>{this.state.isEditModal ? 'Edit' : 'Save'} DSL Query</Modal.Title>
4141                                             </Modal.Header>
4142                                             <Modal.Body>
4143                                                  <Alert id="saveFailure" bsStyle="danger" className={this.state.saveFailureMsg ? 'show' : 'hidden'} onDismiss={() => this.setState({saveFailureMsg: false})}>
4144                                          <h3>Query Save Failed</h3>
4145                                          <p>
4146                                            {this.state.saveFailureMsg}
4147                                          </p>
4148                                      </Alert>
4149                                     <form className={!this.state.showQueryExistsWarning ? 'show' : 'hidden'} id='saveDslQueryForm' name='saveDslQueryForm'>
4150                                       <FormGroup controlId="queryName">
4151                                            <ControlLabel>Query Name</ControlLabel>
4152                                                                                   {!this.state.isEditModal && (<input id='dslNameHelp' type='name' className='form-control' id='queryName' aria-describedby='dslNameHelp' placeholder='Enter query name' value={this.state.queryName} onChange={this.handleQueryNameChange}/>)}
4153                                                                                   {!this.state.isEditModal && (<small id='queryNameHelp' className='form-text text-muted'>Select a name for your saved query, do not reuse names.</small>)}
4154                                                                                   {this.state.isEditModal && (<p>{this.state.queryName}</p>)}
4155                                       </FormGroup>
4156                                       <FormGroup controlId="queryDescription">
4157                                            <ControlLabel>Query Description</ControlLabel>
4158                                            <FormControl componentClass="textarea" id="queryDescription" aria-describedby="queryDescriptionHelp" placeholder="Enter query description" value={this.state.queryDescription} onChange={this.handleQueryDescriptionChange} />
4159                                            <small id="queryDescriptionHelp" className="form-text text-muted">Be as descriptive as possible to describe the purpose of the saved query (this will be searchable)</small>
4160                                       </FormGroup>
4161                                       <FormGroup controlId="category">
4162                                            <ControlLabel>Category</ControlLabel>
4163                                            <input id='category' type="name" className="form-control"  aria-describedby="category of SavedQuery" placeholder="Enter category" value={this.state.category} onChange={this.handleCategoryChange}/>
4164                                       </FormGroup>
4165                                       <FormGroup controlId="privacy_indicator">
4166                                         {this.state.isDataSteward && (<div className="checkbox">
4167                                            <label>
4168                                              <input type="checkbox" checked={this.state.isPublicChecked} onChange={this.onPublicCheckbox.bind(this)} />
4169                                              Public
4170                                            </label>
4171                                         </div>)}
4172                                         <div className={"checkbox " + ((!this.state.isPublicChecked || !this.state.isDataSteward) ? 'show' : 'hidden')}>
4173                                            <label>
4174                                              <input type="checkbox" checked={this.state.isCommunitySharedChecked} onChange={this.onCommunitySharedCheckbox.bind(this)} />
4175                                              Share with Community
4176                                            </label>
4177                                         </div>
4178                                         {!this.state.isDataSteward && (<ControlLabel>Personal Query</ControlLabel>)}
4179                                       </FormGroup>
4180                                       <FormGroup controlId='aggregate'>
4181                                                                                   {this.state.isAggregateChecked && !(this.state.isEditModal || this.state.isSavedQueryFlow) && (<ControlLabel>Aggregate Query</ControlLabel>)}
4182                                                                                   {!this.state.isAggregateChecked && !(this.state.isEditModal || this.state.isSavedQueryFlow) && (<ControlLabel>Standard Query</ControlLabel>)}
4183                                                                                   {(this.state.isEditModal || this.state.isSavedQueryFlow) && (<div className='checkbox'>
4184                                                                                           <label>
4185                                                                                                   <input type='checkbox' checked={this.state.isAggregateChecked} onChange={this.onAggregateCheckbox.bind(this)}/>
4186                                                                                                   Aggregate Query
4187                                                                                           </label>
4188                                                                                   </div>)}
4189                                                                           </FormGroup>
4190                                       <FormGroup controlId='queryDSL'>
4191                                            <ControlLabel>DSL Query</ControlLabel>
4192                                                                                   {!this.state.isEditModal && !this.state.isSavedQueryFlow ? <p>{this.state.value}</p> : <FormControl componentClass='textarea' id='queryDSL' aria-describedby='queryDSLHelp' placeholder='Enter dsl query' value={this.state.value} onChange={this.handleQueryChange} />}
4193                                                                           </FormGroup>
4194                                                                           <FormGroup controlId='templateDetails'>
4195                                                                             <Spinner loading={this.state.enableTreeLoadBusyFeedback}>
4196                                                                                <div className={!this.state.treeLoadErrMsg ? 'show' : 'hidden'}>
4197                                                 <ControlLabel>Configuration Template Details - check for configurable, uncheck for static</ControlLabel>
4198                                                 {Object.keys(this.state.dslConfigArray).map(key => {
4199                                                      return (this.state.dslConfigArray[key].filters).map(filter =>{
4200                                                          return (<div className='checkbox'>
4201                                                                           <label>
4202                                                                                   <input type='checkbox' checked={this.state.staticTemplateFilters.indexOf(key + '|' + filter) === -1} onChange={(e) => {this.onDslConfigCheckbox(e, key + '|' + filter)}} />
4203                                                                                   {key} - {filter}
4204                                                                           </label>
4205                                                                  </div>)
4206                                                      })
4207                                                   })
4208                                                 }
4209                                            </div>
4210                                            <Alert bsStyle="danger" className={this.state.treeLoadErrMsg ? 'show' : 'hidden'}>
4211                                                 <h3>Error Loading Configurable Filters</h3>
4212                                                 <p>
4213                                                   {this.state.treeLoadErrMsg}
4214                                                 </p>
4215                                             </Alert>
4216                                         </Spinner>
4217                                       </FormGroup>
4218                                     </form>
4219                                     <Alert bsStyle="warning" className={this.state.showQueryExistsWarning ? 'show' : 'hidden'} onDismiss={() => this.setState({showQueryExistsWarning: false})}>
4220                                         <h3>Query Name Already Exists</h3>
4221                                         <p>
4222                                           There is already a query with the name {this.state.queryName}, do you wish to overwrite the existing query?
4223                                         </p>
4224                                     </Alert>
4225                                             </Modal.Body>
4226                                             <Modal.Footer className={!this.state.showQueryExistsWarning ? 'show' : 'hidden'}>
4227                                         <Button onClick={this.closeSaveModal}>Close</Button>
4228                                         <Button disabled={this.state.queryName.trim() === '' || this.state.queryDescription.trim() === ''} onClick={() => {this.submitSave()}}>Save</Button>
4229                                 </Modal.Footer>
4230                                 <Modal.Footer className={this.state.showQueryExistsWarning ? 'show' : 'hidden'}>
4231                                         <Button onClick={() => this.setState({showQueryExistsWarning : false})}>No</Button>
4232                                         <Button onClick={() => {this.submitSave(true)}}>Yes</Button>
4233                                 </Modal.Footer>
4234                             </Spinner>
4235                                 </Modal>
4236         </div>
4237                         <div id="jumbotron" className='row'>
4238                                 <div className={'row container-fluid my-4 '  + (this.state.isDSLFlow ? 'show' : 'hidden')}>
4239                                         <div className='col-lg-12'>
4240                                                 <header className='jumbotron'>
4241                                     <h1 className='display-2'><strong>B</strong>uild <strong>Y</strong>our <strong>O</strong>wn <strong>Q</strong>uery</h1>
4242                                     <p className='lead'>
4243                                       On this page you have the ability to craft your own query to retrieve objects from the database.
4244                                       There are help menus in the accordions and a modal triggered from the light bulb icon to help with syntax.
4245                                       There are is also a typeahead feature that will help you build your query as you type, providing valid nodes and attributes to use.
4246                                     </p>
4247                         </header>
4248                                         </div>
4249                                 </div>
4250                                 <div className={'row container-fluid my-4 '  + (this.state.isSavedQueryFlow ? 'show' : 'hidden')}>
4251                     <div className='col-lg-12'>
4252                         <header className='jumbotron'>
4253                                     <h1 className='display-2'>Saved Queries</h1>
4254                                     <p className='lead'>
4255                                       On this page you have the ability to load and run previously saved queries.
4256                                       You can run them as they are saved or choose to load them to replace the filters
4257                                       in the template.
4258                                     </p>
4259                         </header>
4260                     </div>
4261                                 </div>
4262                     </div>
4263                     <div className='row'>
4264                             <div className={'addPadding col-md-12 ' + (this.state.isSavedQueryFlow ? 'show' : 'hidden')}>
4265                                         <div className='row'>
4266                                                 <div className='col-lg-10'>
4267                                                         <Alert id="saveSuccessEdit" bsStyle="success" className={this.state.saveSuccessfulMsg && this.state.isEditModal ? 'show' : 'hidden'} onDismiss={() => this.setState({saveSuccessfulMsg: false})}>
4268                                                                 <h3>Query Saved Successfully</h3>
4269                                                                 <p>
4270                                                                         {this.state.saveSuccessfulMsg}
4271                                                                 </p>
4272                                                         </Alert>
4273                                                 </div>
4274                                         </div>
4275                                 <CustomDSLSaveLoad loadCallback={this.loadCallback} loadBulkCallback={this.loadBulkCallback} setQueriesState={this.setQueriesState} ref={this.saveLoadComponent} isDataSteward={this.state.isDataSteward} isSavedQueryFlow={this.state.isSavedQueryFlow} editCallback={this.editCallback}/>
4276                                 <div className={'col-xs-1 ' + (GlobalExtConstants.INVLIST.IS_ONAP ? 'hidden' : '' )} >
4277                                         <a href={INVLIST.USERGUIDE_URL} target="_blank">
4278                                                 <i className="dsl-hint icon-documents-manual"></i>
4279                                         </a>
4280                                         <pre>User<br />Guide</pre>
4281                                 </div>
4282                                 <div className='col-lg-11'><InfoToggle/></div>
4283                         </div>
4284                         <div className='row'>
4285                                 <div className='col-md-12' id='templateList'>
4286                                         {templateList}
4287                                 </div>
4288                                 <div className='col-md-10'  id='downloadTemplateStatusAlert'>
4289                                         <div className='col-md-6'>
4290                                                 {downloadTemplateStatusAlert}
4291                                         </div>
4292                                         <div className='col-md-6'>
4293                                                 <div style={{float:'right'}}>
4294                                                         {emailCheckbox}
4295                                                 </div>
4296                                                 <div style={{float:'right',margin: '10px'}}>
4297                                                         {downloadAllTemplateQueries}
4298                                                 </div>
4299                                                 <div style={{float:'right',margin: '10px'}}>
4300                                                         {mergedTabs}
4301                                                 </div>                                                                                  
4302                                         </div>
4303                                 </div>                          
4304                                 </div>                          
4305                                 <div className={'addPadding col-md-9 ' + (this.state.isDSLFlow ? 'show' : 'hidden')}>
4306                                         <form onSubmit={this.onAddItem} id='byoqFormForQuery' name='byoqFormForQuery'>
4307                                         <div className='row'>
4308                                                 <div className='col-lg-9 form-group'>
4309                                                     <Alert id="saveSuccess" bsStyle="success" className={this.state.saveSuccessfulMsg ? 'show' : 'hidden'} onDismiss={() => this.setState({saveSuccessfulMsg: false})}>
4310                                                         <h3>Query Saved Successfully</h3>
4311                                                         <p>
4312                                                           {this.state.saveSuccessfulMsg}
4313                                                         </p>
4314                                                     </Alert>
4315                                                         <div id="byoqInput"><label htmlFor='newQuery'>Build Your Own Query</label></div>
4316                                                         <div className={this.state.isTypeahead ? 'show' : 'hidden'}>
4317                                                                 <Autosuggest
4318                                                                 suggestions={this.state.suggestions}
4319                                                                 onSuggestionsFetchRequested={this.onSuggestionsFetchRequested}
4320                                                                 onSuggestionsClearRequested={this.onSuggestionsClearRequested}
4321                                                                 getSuggestionValue={this.getSuggestionValue}
4322                                                                 renderSuggestion={this.renderSuggestion}
4323                                                                 inputProps={inputProps}
4324                                                                 shouldRenderSuggestions={this.shouldRenderSuggestions}
4325                                                                 onSuggestionSelected={this.onSuggestionSelected}
4326                                                                 ref={this.storeInputReference}
4327                                                                 />
4328                                                         </div>
4329                                                         <div className={this.state.isTypeahead ? 'hidden' : 'show'}>
4330                                                                 <FormControl componentClass="textarea"
4331                                                                 rows="4"
4332                                                                 onChange={this.onTextAreaChange}
4333                                                                 style={{width: '655px'}}
4334                                                                 value={this.state.value}
4335                                                                 />
4336                                                         </div>
4337                                                 </div>
4338                                         <div className={'col-xs-1 ' + (GlobalExtConstants.INVLIST.IS_ONAP ? 'hidden' : '' )}>
4339                                                 <a href={INVLIST.USERGUIDE_URL} target="_blank">
4340                                                         <i className="dsl-hint icon-documents-manual"></i>
4341                                                 </a>
4342                                                 <pre>User<br />Guide</pre>
4343                                         </div>
4344                                                 <InfoToggle/>
4345                                                 <div className='col-xs-1'>
4346                                                         <i className='dsl-hint fa fa-question-circle-o' onClick={this.hint} ></i>
4347                                                 </div>
4348                                                 <div className='static-modal'>
4349                                                         <Modal show={this.state.showModal} onHide={this.close}>
4350                                                                 <Modal.Header>
4351                                                                         <Modal.Title>DSL Syntax</Modal.Title>
4352                                                                 </Modal.Header>
4353                                                                 <Modal.Body>
4354                                                                         {
4355                                                                                 this.state.hintHtml.map(hints => {
4356                                                                                 return <div key={hints.notation}>
4357                                                                                 <label>{hints.notation}</label> =>
4358                                                                                 <pre style={{color: 'blue'}}>  {hints.description}</pre>
4359                                                                                 </div>;
4360                                                                                 })
4361                                                                         }
4362                                                                 </Modal.Body>
4363                                                                 <Modal.Footer>
4364                                                                         <Button onClick={this.close}>Close</Button>
4365                                                                 </Modal.Footer>
4366                                                         </Modal>
4367                                                 </div>                                          
4368                                         </div>
4369                                         <div className='row'>
4370                                                 <div className='col-sm-10'>
4371                                                         <button id='runByoqQuery' className='btn btn-primary' type='submit'>Run</button>
4372                                                         { !INVLIST.IS_ONAP &&(<button id='saveByoqQuery' className='btn btn-outline-secondary'  type='button' disabled={this.state.value.trim() === ''} onClick={this.openSaveModal}>Save</button>)}
4373                                                         { INVLIST.isHistoryEnabled && (<button id='historyByoqQuery' className='btn btn-outline-secondary' type='button' disabled={this.state.value.trim() === ''} onClick={this.openHistory}>History</button>)}
4374                                                         <button id='clearByoqQuery' className='btn btn-outline-secondary' type='button' onClick={this.clear}>Clear</button>
4375                                                         <Toggle
4376                                                                 id="typeAheadToggle"
4377                                                                 defaultChecked={this.state.isTypeahead}
4378                                                                 checked={this.state.isTypeahead}
4379                                                                 className='toggle-theme'
4380                                                                 onChange={this.handleTypeaheadChange} />
4381                                                         <span className='addPaddingLeft'>Typeahead</span>
4382                                 </div>
4383                                         </div>
4384                                 </form>
4385                                 <div className={this.state.isInitialLoad ? 'hidden' : 'show'} id='dslInputError'>
4386                                         <Row className={this.state.validInput ? 'hidden' : 'show show-grid'}>
4387                                           <Col md={12}>
4388                                                 <span className='label badge-pill label-danger'><strong>Error </strong>: Please enter a valid query input</span>
4389                                           </Col>
4390                                         </Row>
4391                                 </div>
4392                                 <div className={'checkbox ' + (GlobalExtConstants.INVLIST.IS_ONAP ? 'hidden' : '' )}>
4393                    <label>
4394                      <input type="checkbox" id='aggregateObjectsChkbox' checked={this.state.isAggregateChecked} onChange={this.onAggregateCheckbox.bind(this)} />
4395                      Aggregate Objects
4396                    </label>
4397                    {this.state.isAggregateChecked && (<label>
4398                      <input id='includeAssociatedNodes' type="checkbox" checked={this.state.associatedNodesEnabled} onChange={this.onAssociatedNodesCheckbox.bind(this)} />
4399                      Include Associated Nodes
4400                    </label>)}
4401                 </div>
4402                             <CustomDSLSaveLoad loadCallback={this.loadCallback} loadBulkCallback={this.loadBulkCallback} setQueriesState={this.setQueriesState} ref={this.saveLoadComponentDsl} isDataSteward={this.state.isDataSteward} editCallback={this.editCallback}/>
4403                         </div>
4404                         <div className={'col-lg-2 col-md-12 ' + (this.state.isDSLFlow ? 'show' : 'hidden')}>
4405                 <PanelGroup accordion id='rb-accordion'>
4406                         <Panel eventKey='1'>
4407                         <Panel.Heading>
4408                                 <Panel.Title toggle>+ Simple Queries</Panel.Title>
4409                         </Panel.Heading>
4410                         <Panel.Body collapsible>
4411                                                 <div className='cardwrap'>
4412                                                         <div className='cardWrapHeaderTxt'>
4413                                                                 <label>{this.state.simpleQueries.abstract}</label>
4414                                                         </div>
4415                                                         <div>
4416                                                         {this.state.simpleQueries.notation.map(entry => {
4417                                                                 return (
4418                                                                         <div key={entry.notation}>
4419                                                                         <b><label>{entry.notation}</label></b> =>
4420                                                                         <span style={{color: 'blue'}}> {entry.description}</span>
4421                                                                 </div>
4422                                                                 );
4423                                                         })}
4424                                                         </div>
4425                                                 </div>
4426                         </Panel.Body>
4427                         </Panel>
4428                         <Panel eventKey='2'>
4429                                 <Panel.Heading>
4430                                         <Panel.Title toggle>+ Traversal Queries</Panel.Title>
4431                                 </Panel.Heading>
4432                                 <Panel.Body collapsible>
4433                                                         <div className='cardwrap'>
4434                                                                 <div className='cardWrapHeaderTxt'>
4435                                                                         <label>{this.state.traversalQueries.abstract}</label>
4436                                                                 </div>
4437                                                                 <div>
4438                                                                         {this.state.traversalQueries.notation.map(entry => {
4439                                                                         return (
4440                                                                                 <div key={entry.notation}>
4441                                                                                         <b><label>{entry.notation}</label></b> =>
4442                                                                                         <span style={{color: 'blue'}}> {entry.description}</span>
4443                                                                                 </div>
4444                                                                         );
4445                                                                         })}
4446                                                                 </div>
4447                                                         </div>
4448                                 </Panel.Body>
4449                         </Panel>
4450                         <Panel eventKey='3'>
4451                                 <Panel.Heading>
4452                                         <Panel.Title toggle>+ Union Queries</Panel.Title>
4453                                 </Panel.Heading>
4454                                 <Panel.Body collapsible>
4455                                                         <div className='cardwrap'>
4456                                                                 <div className='cardWrapHeaderTxt'>
4457                                                                         <label>{this.state.unionQueries.abstract}</label>
4458                                                                 </div>
4459                                                                 <div>
4460                                                                         {this.state.unionQueries.notation.map(entry => {
4461                                                                         return (
4462                                                                                 <div key={entry.notation}>
4463                                                                                         <b><label>{entry.notation}</label></b> =>
4464                                                                                         <span style={{color: 'blue'}}> {entry.description}</span>
4465                                                                         </div>
4466                                                                         );
4467                                                                         })}
4468                                                                 </div>
4469                                                         </div>
4470                                 </Panel.Body>
4471                         </Panel>
4472                         <Panel eventKey='4'>
4473                                 <Panel.Heading>
4474                                         <Panel.Title toggle>+ Limit Queries</Panel.Title>
4475                                 </Panel.Heading>
4476                                 <Panel.Body collapsible>
4477                                                         <div className='cardwrap'>
4478                                                                 <div className='cardWrapHeaderTxt'>
4479                                                                         <label>{this.state.limitQueries.abstract}</label>
4480                                                                 </div>
4481                                                                 <div>
4482                                                                         {this.state.limitQueries.notation.map(entry => {
4483                                                                         return (
4484                                                                                 <div key={entry.notation}>
4485                                                                                         <b><label>{entry.notation}</label></b> =>
4486                                                                                         <span style={{color: 'blue'}}> {entry.description}</span>
4487                                                                         </div>
4488                                                                         );
4489                                                                         })}
4490                                                                 </div>
4491                                                         </div>
4492                                 </Panel.Body>
4493                         </Panel>
4494                         <Panel eventKey='5'>
4495                                 <Panel.Heading>
4496                                         <Panel.Title toggle>+ Negation Queries</Panel.Title>
4497                                 </Panel.Heading>
4498                                 <Panel.Body collapsible>
4499                                                         <div className='cardwrap'>
4500                                                                 <div className='cardWrapHeaderTxt'>
4501                                                                         <label>{this.state.negationQueries.abstract}</label>
4502                                                                 </div>
4503                                                                 <div>
4504                                                                         {this.state.negationQueries.notation.map(entry => {
4505                                                                         return (
4506                                                                                 <div key={entry.notation}>
4507                                                                                         <b><label>{entry.notation}</label></b> =>
4508                                                                                         <span style={{color: 'blue'}}> {entry.description}</span>
4509                                                                                 </div>
4510                                                                         );
4511                                                                         })}
4512                                                                 </div>
4513                                                         </div>
4514                                 </Panel.Body>
4515                         </Panel>
4516                         <Panel eventKey='6'>
4517                                 <Panel.Heading>
4518                                         <Panel.Title toggle>+ Topology Queries</Panel.Title>
4519                                 </Panel.Heading>
4520                                 <Panel.Body collapsible>
4521                                                         <div className='cardwrap'>
4522                                                                 <div className='cardWrapHeaderTxt'>
4523                                                                         <label>{this.state.topologyQueries.abstract}</label>
4524                                                                 </div>
4525                                                                 <div>
4526                                                                         {this.state.topologyQueries.notation.map(entry => {
4527                                                                         return (
4528                                                                                 <div key={entry.notation}>
4529                                                                                         <b><label>{entry.notation}</label></b> =>
4530                                                                                         <span style={{color: 'blue'}}> {entry.description}</span>
4531                                                                                 </div>
4532                                                                         );
4533                                                                         })}
4534                                                                 </div>
4535                                                         </div>
4536                                 </Panel.Body>
4537                         </Panel>
4538                 <Panel eventKey='7' className={(this.state.enableRealTime) ? 'show' : 'hidden'}>
4539                   <Panel.Heading>
4540                     <Panel.Title toggle>+ Advanced Queries</Panel.Title>
4541                   </Panel.Heading>
4542                   <Panel.Body collapsible>
4543                     <div className='cardwrap'>
4544                       <div className='cardWrapHeaderTxt'>
4545                         <label>{this.state.advancedQueries.abstract}</label>
4546                       </div>
4547                       <div>
4548                         {this.state.advancedQueries.notation.map(entry => {
4549                           return (
4550                             <div key={entry.notation}>
4551                               <b><label>{entry.notation}</label></b> =>
4552                               <span style={{color: 'blue'}}> {entry.description}</span>
4553                             </div>
4554                           );
4555                         })}
4556                       </div>
4557                     </div>
4558                   </Panel.Body>
4559                 </Panel>
4560                 </PanelGroup>
4561             </div>
4562             </div>
4563             <div className='row'>
4564                         <div className='multipleNodes' id="outputBlock">
4565                         <Spinner loading={this.state.isLoading && this.state.isInitialLoad}>
4566                         </Spinner>
4567                                 <div className={this.state.isInitialLoad ? 'hidden' : 'show'}>
4568                                         <Spinner loading={this.state.isLoading} fullscreen={true}>
4569                                                 <div className={this.state.validInput ? 'show' : 'hidden'}>
4570                                             <Col md={12}>
4571                                                     <h2 className='pre-wrap-text'>{this.state.header}</h2>
4572                                                     <br/>
4573                                                     <h5>Total Results: <strong>{this.state.totalResults}</strong></h5>
4574                                                 </Col>
4575                                                 {this.state.showResults && <div className="addPaddingTop" >
4576                                                     <OutputToggle scope={this} visualDisabled={this.state.totalResults > PAGINATION_CONSTANT}/>
4577                                                 </div> }
4578                                                 {!this.state.isAggregate && (<div id="standardOutput" className="col-md-12">
4579                                                     <Row className={this.state.showResults ? 'show' : 'hidden'}>
4580                                                         <Col md={8} className={this.state.showPagination ? 'show' : 'hidden'}>
4581                                                                 <Pagination
4582                                                                         activePage={this.state.activePage}
4583                                                                         itemsCountPerPage={PAGINATION_CONSTANT.RESULTS_PER_PAGE}
4584                                                                         totalItemsCount={this.state.totalResults}
4585                                                                         pageRangeDisplayed={PAGINATION_CONSTANT.PAGE_RANGE_DISPLAY}
4586                                                                         onChange={this.handlePageChange} />
4587                                                         </Col>
4588                                                         <Col md={2} className='text-right'>
4589                                                                 <OverlayTrigger  placement='top' overlay={<Tooltip id='tooltip-top'>{this.downloadAllTooltip}</Tooltip>}>
4590                                                         <span className="d-inline-block" style={{display: 'inline-block'}}>
4591                                                                                 <Button bsSize='small' onClick={() => {this.getAllExcels(this.state.downloadCount)}}>
4592                                                                                         Download XLSX <i className='icon-documents-downloadablefile'></i>
4593                                                                 </Button>
4594                                                                         </span>
4595                                                                 </OverlayTrigger>
4596                                                         </Col>
4597                                                         <Col md={2} className='text-right'>
4598                                                             <OverlayTrigger  placement='top' overlay={<Tooltip id='tooltip-top'>{this.downloadRangeTooltip}</Tooltip>}>
4599                                                 <span className="d-inline-block" style={{display: 'inline-block'}}>
4600                                                                                 <Button bsSize='small' onClick={this.openDownloadRange}>
4601                                                                                 Download XLSX (Range) <i className='icon-documents-downloadablefile'></i>
4602                                                                         </Button>
4603                                                                 </span>
4604                                                             </OverlayTrigger>
4605                                                         </Col>
4606                                                     </Row>
4607                                                     <hr/>
4608                                                     <div className={'addPaddingTop alert alert-danger ' +(this.state.errorResults ? 'show' : 'hidden')} role="alert">
4609                               An error occurred, please try again later. If this issue persists, please contact the system administrator. {this.state.errorMessage}
4610                             </div>
4611                                                     <Row className={this.state.noResults ? 'show' : 'hidden'}>
4612                                                         <Col md={12}>
4613                                                                 <h2>No Results Found</h2>
4614                                                         </Col>
4615                                                     </Row>
4616                                                     <div className={this.state.errorResults || this.state.noResults ? 'hidden' : 'show'}>
4617                                                         <div className='nodes container-fluid'>
4618                                                                 <div className='row-dsl'>
4619                                                                         {nodes}
4620                                                                 </div>
4621                                                         </div>
4622                                                     </div>
4623                                                     <Row className={this.state.showPagination ? 'show' : 'hidden'}>
4624                                                         <Col md={6}>
4625                                                                 <Pagination
4626                                                                         activePage={this.state.activePage}
4627                                                                         itemsCountPerPage={PAGINATION_CONSTANT.RESULTS_PER_PAGE}
4628                                                                         totalItemsCount={this.state.totalResults}
4629                                                                         pageRangeDisplayed={PAGINATION_CONSTANT.PAGE_RANGE_DISPLAY}
4630                                                                         onChange={this.handlePageChange} />
4631                                                         </Col>
4632                                                     </Row>
4633                                                 </div>)}
4634                                                 {this.state.isAggregate && (<div id="aggregateOutput">
4635                                         <Row className={ this.state.errorResults || this.state.noResults ? 'hidden' : 'show'}>
4636                                                                 <Col md={8} className={this.state.showPagination ? 'show' : 'hidden'}>
4637                                                                 <Pagination
4638                                                                         activePage={this.state.aggregateActivePage}
4639                                                                         itemsCountPerPage={PAGINATION_CONSTANT.RESULTS_PER_PAGE}
4640                                                                         totalItemsCount={this.state.totalResults}
4641                                                                         pageRangeDisplayed={PAGINATION_CONSTANT.PAGE_RANGE_DISPLAY}
4642                                                                         onChange={this.handlePageChange} />
4643                                                         </Col>
4644                                                                 <Col md={2} className='text-right'>
4645                                                                 <OverlayTrigger  placement='top' overlay={<Tooltip id='tooltip-top'>{this.downloadAllTooltip}</Tooltip>}>
4646                                                         <span className="d-inline-block" style={{display: 'inline-block'}}>
4647                                                                                 <Button bsSize='small' onClick={() => {this.downloadAllAggregate(this.state.downloadCount)}}>
4648                                                                                         Download XLSX <i className='icon-documents-downloadablefile'></i>
4649                                                                                 </Button>
4650                                                                         </span>
4651                                                                 </OverlayTrigger>
4652                                                         </Col>
4653                                                                 <Col md={2} className='pull-right text-right'>
4654                                     <OverlayTrigger  placement='top' overlay={<Tooltip id='tooltip-top'>Download All Aggregate Objects By Custom Range Selection</Tooltip>}>
4655                                         <span className="d-inline-block" style={{display: 'inline-block'}}>
4656                                                         <Button bsSize='small' onClick={this.openDownloadRange}>
4657                                                         Download XLSX (Range) <i className='icon-documents-downloadablefile'></i>
4658                                                 </Button>
4659                                         </span>
4660                                     </OverlayTrigger>
4661                                 </Col>
4662                             </Row>
4663                             <hr/>
4664                             <div className={'addPaddingTop alert alert-danger ' + (this.state.errorResults ? 'show' : 'hidden')} role="alert">
4665                                     An error occurred, please try again later. If this issue persists, please contact the system administrator. {this.state.errorMessage}
4666                                   </div>
4667                             <Row className={this.state.noResults ? 'show' : 'hidden'}>
4668                                 <Col md={12}>
4669                                         <h2>No Results Found</h2>
4670                                 </Col>
4671                             </Row>
4672                             <div className={this.state.errorResults || this.state.noResults ? 'hidden' : 'show'}>
4673                                 <div className='nodes container-fluid'>
4674                                         <div className='row-dsl'>
4675                                                 {nodes}
4676                                                 <div className={this.state.viewName === "VisualLayout" ? 'show' : 'hidden'}>
4677                                                     <OutputVisualization identifier="currentStateAggregate" width={ window.outerWidth * 0.8 } height="1200" overflow="scroll"/>
4678                                         </div>
4679                                         </div>
4680                                 </div>
4681                             </div>
4682                                                         <Row className={this.state.showPagination ? 'show' : 'hidden'}>
4683                                                         <Col md={6}>
4684                                                                 <Pagination
4685                                                                         activePage={this.state.aggregateActivePage}
4686                                                                         itemsCountPerPage={PAGINATION_CONSTANT.RESULTS_PER_PAGE}
4687                                                                         totalItemsCount={this.state.totalResults}
4688                                                                         pageRangeDisplayed={PAGINATION_CONSTANT.PAGE_RANGE_DISPLAY}
4689                                                                         onChange={this.handlePageChange} />
4690                                                         </Col>
4691                                                     </Row>
4692                                                 </div>)}
4693                                                 </div>
4694                                                         <Spinner loading={this.state.enableModelBusyFeedback}>
4695                                                                 {downloadRangeModel}
4696                                                         </Spinner>
4697                                         </Spinner>
4698                                 </div>
4699                                 <div className='row'>
4700                                         <div className='col-sm-10'></div>
4701                                 </div>
4702                         </div>
4703                         </div>
4704                 </div>
4705         </div>
4706   );
4707         }
4708 }
4709
4710 export default CustomDsl;