aboutsummaryrefslogtreecommitdiffstats
path: root/lifecyclemgr/src/main/webapp/lifecyclemgr/js/DataService.js
blob: f2ff54837397aa4264c295a8513f89b175721505 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
/*

    Copyright 2017, Huawei Technologies Co., Ltd.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

            http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

*/

app.factory("DataService", function($http, $log){
    var lcData = null;
    var createParamJsonObj = {
        templateId:'',
        parameters: {}
    };
    var tableDataLoaded = false;
    
    return {
        setTableDataLoaded : function() {
            tableDataLoaded = true;
        },
        getTableDataLoaded : function() {
            return tableDataLoaded;
        },
        getCreateParamJsonObj: function(){
            return createParamJsonObj;
        },
        loadGetServiceData : function() {

            //load main Table
            return $http({
                url: '/openoapi/servicegateway/v1/services',
                //url: 'http://localhost:5000/api/getLCData',
                method: 'GET',
                headers: {'Content-Type': 'application/json'}

                /*url: '/openoapi/inventory/v1/services',
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                data: JSON.stringify({'sort': [],
                 'pagination': 0,
                 'pagesize': 10000,
                 'condition': {},
                 'serviceId': ""})*/
            }).then(function(response){
                //$log.info(response);
                lcData = response.data;
                return response;
            });
        },
        getSavedLCData : function(id){
            var returnData = null;
            if(lcData) {
                for (var i = 0; i < lcData.length; i++) {
                    if(lcData[i].serviceId == id) {
                        returnData = lcData[i].inputParameters;
                        break;
                    }
                }
                return returnData;
            }
            else
                return null;
        },
        getOverlayData : function() {
            return $http({
                url: '/openoapi/sdnooverlayvpn/v1/site2dc-vpn',
                //url: 'http://localhost:5000/api/getOverlayVPNData',
                method: 'GET',
                headers: {'Content-Type': 'application/json'}
            }).then(function(response){
                //$log.info(response);
                return response.data;
            });
        },
        getUnderlayData : function() {
            return $http({
                url: '/openoapi/sdnol3vpn/v1/l3vpns',
                //url: 'http://localhost:5000/api/getUnderlayVPNData',
                method: 'GET',
                headers: {'Content-Type': 'application/json'}
            }).then(function(response){
                //$log.info(response);
                return response.data;
            });
        },
        loadServiceDetails : function(id) {
            return JSON.parse('[{"id":"12345", "name":"sdno"}, {"id":"23456", "name":"gso"},{"id":"12345", "name":"nfvo"}]');
        },
        loadNfvoServiceDetails : function(id) {
            return JSON.parse('{"vnfInfoId": [{ "vnfInstanceId": "123", "vnfInstanceName": "vnf instance 1", "vnfProfileId": "321" }, { "vnfInstanceId": "123", "vnfInstanceName": "vnf instance 1", "vnfProfileId": "321" }],  "vlInfo": [{ "networkResource": {"resourceName": "network resource 1"}, "linkPortResource": { "resourceName": "link port resource 1"}}, { "networkResource": {"resourceName": "network resource 1"}, "linkPortResource": { "resourceName": "link port resource 1"}}], "vnffgInfo": [{"vnfId": "vnfid-123", "virtualLinkId": "virtual link 123", "cpId": "cp id 123", "nfp": "nfp 123"}, {"vnfId": "vnfid-123", "virtualLinkId": "virtual link 123", "cpId": "cp id 123", "nfp": "nfp 123"}]}');
        },

        generateTemplatesComponent : function() {
            //dropdown data
            return $http({
                url: '/openoapi/catalog/v1/servicetemplates',
                //url: 'http://localhost:5000/api/getTemplateData',
                method: 'GET',
                headers: {'Content-Type': 'application/json'}
            }).then(function(response){
                //$log.info(response);
                return response.data;
            });
        },
	
        generateCreateParameters : function(template) {
            // For Template parameters tab in popup
            return $.when(fetchCreateParameters(template.serviceTemplateId))
            .then(function(createParam) {
                // set the create param object
                createParamJsonObj = createParam;
                // convert the create param to UI.
                return convertCreateParamsToUI('create', createParam.parameters);

            });
        },

        createService : function(serviceBaseInfo) {
            if (!checkInputs('create', createParamJsonObj.parameters)) {
                return {status:'checkfailed'};
            }
            var sengMsgObj = collectCreateParamfromUI('', 'create', createParamJsonObj.parameters);
            var gatewayService = '/openoapi/servicegateway/v1/services';
            return createServiceInstance(serviceBaseInfo, sengMsgObj);            
        },
        
        deleteService : function(serviceId) {
            return deleteServiceInstance(serviceId);    
        },
        scaleService: function (nsInstanceId, scaleType, aspectId, numberOfSteps, resultHandleFun) {
            scaleServiceInstance(nsInstanceId, scaleType, aspectId, numberOfSteps, resultHandleFun);
        }
    }
});

/**
 * init parameter tab
 * @returns
 */
function initParameterTab() {
    // Service template was not changed. Do not re-initiate the parameter tab.
    if (!templateParameters.changed) {
        return;
    }
    var templateId = $("#svcTempl").val();
    if ('select' === templateId) {
        document.getElementById("templateParameterTab").innerHTML = '';
        return;
    }
    $.when(fetchCreateParameters(templateId))
    .then(function(createParam) {
        // set the create param object
        templateParameters.paramJsonObj = createParam.parameters;
        // convert the create param to UI.
        var components = convertCreateParamsToUI('create', createParam.parameters);
        document.getElementById("templateParameterTab").innerHTML = components;
        templateParameters.changed = false;
    });
}

/**
 * generate the template to create parameters object
 * 
 * @param templateId
 *            the template id
 * @returns
 */
function fetchCreateParameters(templateId) {
    //return $.getJSON("./conf/queryCreateParams.json");
    var uri = '/openoapi/servicegateway/v1/createparameters/' + templateId;
    return $.ajax({
        type : "GET",
        url : uri,
        error : function(xhr, ajaxOptions, thrownError) {
            showErrorMessage("Generate parameters failed.", xhr.responseText);
        } 
    });
}

/**
 * convert the template params obj to html UI string
 * 
 * @param identify the object identify, it should be '' when called
 * @return the html component string
 */
function convertCreateParamsToUI(identify, createParam) {
    var components = '';
    // convert host to UI
    if (undefined !=  createParam.domainHost && 'enum' === createParam.domainHost.type) {
        components = components
                + generateParamComponent(createParam.nodeType, identify,
                        createParam.domainHost, false);
    }
    // convert own locationConstraints to UI
    if(undefined != createParam.nsParameters.locationConstraints){
        createParam.nsParameters.locationConstraints.forEach(function(param) {
            components = components
                    + generateParamComponent(createParam.nodeType,
                            identify, param.locationConstraints.vimId, false);
        });
    }
    
    // convert own param to UI
    createParam.nsParameters.additionalParamForNs
            .forEach(function(param) {
                components = components
                        + generateParamComponent(createParam.nodeType,
                                identify, param, false);
            });
    // convert segments to UI
    createParam.segments.forEach(function(segment) {
        // each segment in a field set.
        components = components + '<fieldset style="margin-left:25px;"><legend>'
                + segment.nodeTemplateName + '</legend>';
        // the identify for segment
        var segmentIdentify = '' == identify ? segment.nodeTemplateName
                : identify + '_' + segment.nodeTemplateName;
        // convert segment to UI
        components = components
                + convertCreateParamsToUI(segmentIdentify, segment);
        components = components + '</fieldset>';
    });
    return components;
}


/**
 * for each required parameter it could not be empty
 * @param identify the identify of a segment
 * @param createParam the create param object 
 * @returns the check result
 */
function checkInputs(identify, createParam) {
    //check domain host
    if (undefined !=  createParam.domainHost && 'enum' === createParam.domainHost.type) {
        var value = collectParamValue(identify, createParam.domainHost);
        if ('select' == value) {
            var name = getParamLabel(createParam.nodeType, createParam.domainHost);
            alert( name + ' is required.')
            return false;
        }
    }
    //check location constraints
    if(undefined != createParam.nsParameters.locationConstraints){
        for(var i= 0; i < createParam.nsParameters.locationConstraints.length; i++){    
            var param = createParam.nsParameters.locationConstraints[i].locationConstraints.vimId;
            var value = collectParamValue(identify, param);
            if('true' === param.required && ('' === value || ('enum' == param.type && 'select' == value))){
                // the param resource key is nodeType.paramName
                var name = getParamLabel(createParam.nodeType, param);
                alert(name + ' is required.')
                return false;
            }
        }
    }

    // check parameters
    for(var i= 0; i < createParam.nsParameters.additionalParamForNs.length; i++){    
        var param = createParam.nsParameters.additionalParamForNs[i];
        var value = collectParamValue(identify, param);
        if('true' === param.required && ('' === value || ('enum' == param.type && 'select' == value))){
            // the param resource key is nodeType.paramName
            var name = getParamLabel(createParam.nodeType, param);
            alert(name + ' is required.')
            return false;
        }
    }
    // get segments param value from UI
    var segmentcheckResult = true;
    for(var i= 0; i < createParam.segments.length; i++){
        var segment = createParam.segments[i];
        // the identify for segment
        var segmentIdentify = '' == identify ? segment.nodeTemplateName
                : identify + '_' + segment.nodeTemplateName;
        segmentcheckResult = checkInputs(segmentIdentify, segment);
        if (!segmentcheckResult) {
            break;
        }
    }
    return segmentcheckResult;
}


/**
 * convert the template params obj to html UI string
 * 
 * @param identify the object identify, it should be different every time
 * @return the html component string
 */
function collectCreateParamfromUI(parentHost,identify, createParam) {
    // the create params used for create msg
    var paramSentObj = {
            domainHost:'',
            nodeTemplateName:'',
            nodeType:'',
            segments:[],
            nsParameters:{}
    };  
    // get the domain value
    if (undefined !=  createParam.domainHost && 'enum' === createParam.domainHost.type) {
        var domain = collectParamValue(identify, createParam.domainHost);
        paramSentObj.domainHost = collectParamValue(identify, createParam.domainHost)
    }
    //if parent domainHost is not '' and local domain host is'', it should be setted as parent
    if('' != parentHost && '' == paramSentObj.domainHost){
        paramSentObj.domainHost = parentHost;
    }
    paramSentObj.nodeTemplateName = createParam.nodeTemplateName;
    paramSentObj.nodeType = createParam.nodeType;

    //get location constraints
    if(undefined != createParam.nsParameters.locationConstraints){
        paramSentObj.nsParameters['locationConstraints'] = [];
        createParam.nsParameters.locationConstraints.forEach(function(param) {
            var locationConstraints = {};
            locationConstraints['vnfProfileId'] = param.vnfProfileId;
            locationConstraints['locationConstraints'] = {};
            locationConstraints.locationConstraints['vimId'] = collectParamValue(identify, param.locationConstraints.vimId);
            paramSentObj.nsParameters.locationConstraints.push(locationConstraints);
        });
    }

    paramSentObj.nsParameters['additionalParamForNs'] = {};
    // get own param value from UI
    createParam.nsParameters.additionalParamForNs.forEach(function(param) {
        paramSentObj.nsParameters.additionalParamForNs[param.name] = collectParamValue(identify, param);
    });
    // get segments param value from UI
    createParam.segments.forEach(function(segment) {
        // the identify for segment
        var segmentIdentify = '' == identify ? segment.nodeTemplateName
                : identify + '_' + segment.nodeTemplateName;
        var segmentObj = collectCreateParamfromUI(paramSentObj.domainHost, segmentIdentify, segment);
        paramSentObj.segments.push(segmentObj);
    });
    return paramSentObj;
}

/**
 * get a param value
 * @param identify the identify of a segment
 * @param param the param object 
 * @returns the value of the param
 */
function collectParamValue(identify, param) {
    var value = $('#' + getParamId(identify, param)).val();
    return value;
}

/**
 * get the param id in ui
 * @param identify
 * @param param
 * @returns
 */
function getParamId(identify, param) {
    return '' ===identify ? param.name : identify + '_' + param.name;
}

/**
 * get the resource string of a param.
 * @param nodeType node type
 * @param param param object
 * @returns resource string
 */
function getParamLabel(nodeType, param) {
    var name = $.i18n.prop(nodeType + '.' + param.name);
    if (name.length === 0 || name.slice(0, 1) === '[') {
        name = param.name;
    }
    return name;
}
/**
 * convert combox component
 * 
 * @param inputPara
 * @param items
 * @param stringReadOnly
 * @returns
 */
function generateParamComponent(nodeType, identify, param, strReadOnly) {
    // the param resource key is nodeType.paramName
    var name = getParamLabel(nodeType, param);
    var id = getParamId(identify,param);
    var component = '';
    if (param.type != 'enum') {
        component = '<div class="mT15 form-group row-content" style="margin-left:0px;">'
                + '<label class="col-sm-6 control-label labelstyle">'
                + '<span>' + name + '</span>' + generateRequiredLabel(param)
                + '</label>' 
                + '<div class="col-sm-6"><input type="text" id="' + id
                + '" name="parameter description" class="form-control" placeholder="'
                + '"value="' + param.defaultValue;
        if(strReadOnly){
            component = component + '" readonly="' + strReadOnly + '"/>'+ '</div></div>';
        }else{
            component = component + '"/>'+ '</div></div>';
        }
                
    } else if (param.type === 'enum') {
        component = '<div class="form-group row-content" style="margin-left:0px;margin-bottom:5px;">'
                + '<label class="col-sm-6 control-label labelstyle">'
                + '<span>' + name + '</span>'
                + generateRequiredLabel(param)
                + '</label>'
                + '<div class="col-sm-6">'
                + '<select class="form-control" style ="padding-top: 0px;padding-bottom: 0px;"'
                + ' id="' + id + '" name="' + param.name + '" value="' + param.defaultValue 
                + '">'
                + this.transformToOptions(param.range)
                + '</select></div></div>';
    }
    return component;
}

/**
 * transfer the enum range to html body
 * @param items the map of the range
 * @returns the html string
 */
function transformToOptions(items) {
    var options = '<option value="select">--select--</option>';
    var i;
    for ( var key in items) {
        var option = '<option value="' + key + '">' + items[key] + '</option>';
        options = options + option;
    }
    return options;
}

/**
 * generate required identify to html string
 * @param parameter the parameter object
 * @returns the html string 
 */
function generateRequiredLabel(parameter) {
    var requiredLabel = '';
    if (parameter.required === 'true') {
        requiredLabel = '<span class="required">*</span>';
    }
    return requiredLabel;
}

/**
 * create service
 * @param sengMsgObj the parameters
 * @returns 
 */
function createServiceInstance(serviceBaseInfo, sengMsgObj) {
    var defer = $.Deferred();
    var parameter = {
        'service' : {
            'name' :  serviceBaseInfo.name,
            'description' : serviceBaseInfo.description,
            'serviceDefId' : '', //no need now, reserved
            'templateId' :  serviceBaseInfo.templateId,
            'parameters' : sengMsgObj
        }
    };
    var serviceGatewayUri = '/openoapi/servicegateway/v1/services';
    $.when($.ajax({
        type : "POST",
        url : serviceGatewayUri,
        contentType : "application/json",
        dataType : "json",
        data : JSON.stringify(parameter),
        error : function(xhr, ajaxOptions, thrownError) {
            showErrorMessage("Create service failed.", xhr.responseText);
        }
    }))
    .then(function(response) {
        return queryProgress('create service', response.service.serviceId,response.service.operationId);
    }).then(function(result){
        defer.resolve(result);
    });
    return defer;
}

/**
 * sent delete instance msg
 * @param serviceId the service id
 * @returns
 */
function deleteServiceInstance(serviceId) {
    var defer = $.Deferred();
    var deleteUrl = '/openoapi/servicegateway/v1/services/' + serviceId;
    var parameter = {};
    $.when($.ajax({
        type : "DELETE",
        url : deleteUrl,
        contentType : "application/json",
        dataType : "json",
        data : JSON.stringify(parameter),
        error : function(xhr, ajaxOptions, thrownError) {
            showErrorMessage("Delete service failed.", xhr.responseText);
        }        
    }))
    .then(function(response) {
        return queryProgress('delete service', serviceId,response.operationId);
    }).then(function(result){
        defer.resolve(result);
    });
    return defer;
}

/**
 * query progress of the operation 
 * @param operation the operation string
 * @param serviceId the service id
 * @param operationId the operation id
 * @returns
 */
function queryProgress(operation, serviceId, operationId) {
    //show the progress dialog
    $( "#idProgressTitle" ).text(operation);
    $( "#progressContent" ).text('status:');            
    $( "#progressbar" ).attr("style","width: 0%");
    $( "#progressDialog" ).modal({backdrop:'static', keyboard:false});    
    //set a timer for query operation
    var defer = $.Deferred();
    var queryProgressUril = '/openoapi/servicegateway/v1/services/' + serviceId + '/operations/' + operationId;
    var timerDefer = $.Deferred();
    var timeout = 3600000;
    var fun = function() {
        if (timeout === 0) {
            timerDefer.resolve({
                status : 'error',
                reason : operation + ' timeout!',
            });
            return;
        }
        timeout = timeout - 1000;
        $.when($.ajax({
            type : "GET",
            url : queryProgressUril,
            error : function(xhr, ajaxOptions, thrownError) {
                showErrorMessage("Query progress failed.", xhr.responseText);
            } 
        }))
        .then(function(response) {
            //update progress
            $( "#progressbar" ).attr("style","width: " + response.operation.progress.toString() + "%");
            $( "#progressValue" ).text(response.operation.progress.toString() + '%');
            $( "#progressContent" ).text('status: ' + response.operation.operationContent);            
            if (response.operation.result == 'finished' || response.operation.result == 'error') {
                timerDefer.resolve({
                    status : response.operation.result ,
                    reason : response.operation.reason
                });
            }
        });
    };
    var timerId = setInterval(fun, 1000);
    $.when(timerDefer)
    .then(function(responseDesc) {
        clearInterval(timerId);
        $('#progressDialog').modal('hide');
        defer.resolve({
            status : responseDesc.status,
            reason : responseDesc.reason,
            serviceId:serviceId
        });

    });
    return defer; 
}


/**
 * convert the input parameters to ui
 * @param identify the identify of a segment
 * @param createParam the create param object 
 * @returns the check result
 */
function convertInputsToUI(parentHost, identify, serviceParam) {
    var components = '';
    // convert host to UI
    if (undefined !=  serviceParam.domainHost && '' != serviceParam.domainHost && parentHost != serviceParam.domainHost) {
        var param ={
            name:'domainHost',
            type:'string',
            defaultValue:getShowVal('domainHost', serviceParam.domainHost),
            required:false            
        }
        components = components + generateParamComponent(serviceParam.nodeType, identify,
                param, true);
    }
    //convert location constraints to UI
    if(undefined != serviceParam.nsParameters.locationConstraints){        
        serviceParam.nsParameters.locationConstraints.forEach(function(param) {
            var showValue = getShowVal('location', param.locationConstraints.vimId)
            var param ={
                    name: param.vnfProfileId + '_Location',
                    type:'string',
                    defaultValue:showValue,
                    required:false            
                }
            components = components + generateParamComponent(serviceParam.nodeType,
                            identify, param, true);
        });
    }

    // convert own param to UI
    for(var key in serviceParam.nsParameters.additionalParamForNs ){
        var param ={
                name: key,
                type:'string',
                defaultValue:getShowVal(key, serviceParam.nsParameters.additionalParamForNs[key]),
                required:false            
            }
        components = components + generateParamComponent(serviceParam.nodeType,
                        identify, param, true);
    }
    // convert segments to UI
    serviceParam.segments.forEach(function(segment) {
        // each segment in a field set.
        components = components + '<div class="mT15 form-group"><fieldset style="margin-left:25px;"><legend>'
                + segment.nodeTemplateName + '</legend>';
        // the identify for segment
        var segmentIdentify = '' == identify ? segment.nodeTemplateName
                : identify + '_' + segment.nodeTemplateName;
        // convert segment to UI
        components = components
                + convertInputsToUI(serviceParam.domainHost, segmentIdentify, segment);
        components = components + '</fieldset></div>';
    });
    return components;
}

function getShowVal(paramName, paramValue){
    if(paramName == 'domainHost'){
        return getHostNameByVal(paramValue);
    }
    else if(paramName == 'location'){
        return getVimNameById(paramValue);
    }
    else if(paramName == 'sdncontroller'){
        return getSdnControllerNameById(paramValue);
    }
    else{
        return paramValue;
    }
}

function getHostNameByVal(hostDomain){
     var requestUrl ="/openoapi/servicegateway/v1/domains";
      var returnObj = '';
      $.ajax({
              type : "GET",
              async: false,
              url : requestUrl,
              contentType : "application/json",
              success : function(jsonobj) {
                jsonobj.forEach(function(host){
                    if(host.host == hostDomain){
                          returnObj = host.name;
                    }
                });
              },
              error : function(xhr, ajaxOptions, thrownError) {
                 showErrorMessage("Query host failed.", xhr.responseText);
              }
          });
      return returnObj;
}

//get the vim name by id.
function getVimNameById(vimId){
  var requestUrl ="/openoapi/extsys/v1/vims/" + vimId;
  var returnObj;
  $
      .ajax({
          type : "GET",
          async: false,
          url : requestUrl,
          contentType : "application/json",
          success : function(jsonobj) {
              // TODO return according to the json data received.
              returnObj = jsonobj.name;
          },
          error : function(xhr, ajaxOptions, thrownError) {
              showErrorMessage("Query vims failed.", xhr.responseText);
          }
      });
  return returnObj;
}

//get the sdn controller name by id.
function getSdnControllerNameById(sdnControllerId){
  var requestUrl ="/openoapi/extsys/v1/sdncontrollers/" + sdnControllerId;
  var returnObj;
  $
      .ajax({
          type : "GET",
          async: false,
          url : requestUrl,
          contentType : "application/json",
          success : function(jsonobj) {
              // TODO return according to the json data received.
              returnObj = jsonobj.name;
          },
          error : function(xhr, ajaxOptions, thrownError) {
              showErrorMessage("Query sdn controllers failed.", xhr.responseText);
          }
      });
  return returnObj;
}



/**
 * show error dialog
 * @param title the title 
 * @param result the result
 * @returns
 */
function showErrorMessage(title, result) {
    //show the error dialog
    $( "#errorDialogTitle" ).text(title);
    if(undefined != result.reason){
        $( "#errorDialogReason" ).text(result.reason);     
    }
    else{
        $( "#errorDialogReason" ).text(result);     
    }
    $( "#errorDialog" ).modal({backdrop:'static', keyboard:false});    
}

/**
 * generate the template to create parameters object
 * 
 * @param templateId the template id
 * @returns
 */
function queryService(serviceId) {
    var uri = '/openoapi/servicegateway/v1/services/' + serviceId;
    return $.ajax({
        type : "GET",
        url : uri,
        error : function(xhr, ajaxOptions, thrownError) {
            showErrorMessage("Query service failed.", xhr.responseText);
        } 
    });
}

function queryServiceData(){
    var returnVal = [];
    var requestUrl = "/openoapi/servicegateway/v1/services";
    $
        .ajax({
            type : "GET",
            url : requestUrl,
            async: false,
            contentType : "application/json",
            success : function(jsonobj) {
                // TODO return according to the json data received.
                returnVal =  jsonobj;
            },
            error : function(xhr, ajaxOptions, thrownError) {
                showErrorMessage("Query services fail",xhr.responseText);
            }
        });
    return returnVal;
}

function scaleServiceInstance(nsInstanceId, scaleType, aspectId, numberOfSteps, resultHandleFun) {
    var parameter = {
        'nsInstanceId': nsInstanceId,
        'scaleType': 'SCALE_NS',
        'scaleNsData': [
            {
                'scaleNsByStepsData': [
                    {
                        'scalingDirection': scaleType,
                        'aspectId': aspectId,
                        'numberOfSteps': numberOfSteps
                    }
                ]
            }
        ]
    };
    var nfvoUri = '/openoapi/nslcm/1.0/ns/' + nsInstanceId + '/scale';
    $.when(
        $.ajax({
            type: "POST",
            url: nfvoUri,
            contentType: "application/json",
            dataType: "json",
            data: JSON.stringify(parameter)
        })
    ).then(
        function (response) {
            var jobId = response.jobID;
            //show the progress dialog
            return queryScaleProgress(jobId);
        }
    ).then(function (response) {
        resultHandleFun(response);
    });
}

function queryScaleProgress(jobId) {
    //show the progress dialog
    var operation = 'scale network service';
    $("#idScaleProgressTitle").text(operation);
    $("#scaleProgressContent").text('status:');
    $("#scaleProgressbar").attr("style", "width: 0%");
    $("#scaleProgressDialog").modal({backdrop: 'static', keyboard: false});
    //set a timer for query operation
    var defer = $.Deferred();
    var queryProgressUri = jobStatusUri(jobId);
    var timerDefer = $.Deferred();
    var timeout = 3600000;
    var fun = function () {
        if (timeout === 0) {
            timerDefer.resolve({
                status: 'error',
                reason: operation + ' timeout!',
            });
            return;
        }
        timeout = timeout - 1000;
        $.when($.ajax({
            type: "GET",
            url: queryProgressUri
        }))
            .then(function (response) {
                //update progress
                $("#scaleProgressbar").attr("style", "width: " + response.responseDescriptor.progress.toString() + "%");
                $("#scaleProgressValue").text(response.responseDescriptor.progress.toString() + '%');
                $("#scaleProgressContent").text('status: ' + response.responseDescriptor.statusDescription);
                if (response.responseDescriptor.status == 'finished' || response.responseDescriptor.status == 'error') {
                    timerDefer.resolve({
                        status: response.responseDescriptor.status,
                        reason: response.responseDescriptor.errorCode
                    });
                }
            });
    };
    var timerId = setInterval(fun, 1000);
    $.when(timerDefer)
        .then(function (responseDesc) {
            clearInterval(timerId);
            $('#scaleProgressDialog').modal('hide');
            defer.resolve({
                status: responseDesc.status,
                reason: responseDesc.reason
            });

        });
    return defer;
}

/**
 * generate url for querying operation status
 * @param jobId
 * @param responseId
 * @returns
 */
function jobStatusUri(jobId, responseId) {
    var responsePara = '';
    if (undefined !== responseId) {
        responsePara = '&responseId=' + responseId;
    }
    return '/openoapi/nslcm/v1/jobs/' + jobId + responsePara;
}