Link DCAE MOD design tool to Acumos Adapter
[dcaegen2/platform.git] / mod / designtool / designtool-web / src / main / webapp / js / jquery / dcae-mod.js
1 /*
2 ============LICENSE_START=======================================================
3 Copyright (c) 2019 AT&T Intellectual Property. All rights reserved.
4 ================================================================================
5 Licensed under the Apache License, Version 2.0 (the "License");
6 you may not use this file except in compliance with the License.
7 You may obtain a copy of the License at
8
9      http://www.apache.org/licenses/LICENSE-2.0
10
11 Unless required by applicable law or agreed to in writing, software
12 distributed under the License is distributed on an "AS IS" BASIS,
13 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 See the License for the specific language governing permissions and
15 limitations under the License.
16 ============LICENSE_END=========================================================
17 */
18
19 console.log("loading dcae-mod");
20
21     var dt_id;
22
23     /**
24     * @desc: on load of page, makes submit button disabled. Also makes an api call to get the host IP of the current instance
25     */
26     $(document).ready(function (){
27         if(dt_id == null){   $('#operate-submit-btn').prop('disabled', true);   }
28
29         getDistributionTargets();
30     });
31
32    /**
33     * common function to reuse : invokes api to get new updates list environments.
34     * @desc: Makes the select dropdown empty first. Then manually add Placeholder as first/default Option.
35     *        And then dynamically add list of Environments as Options.
36     */
37     function getDistributionTargets(){
38         var select = document.getElementById("environmentType");
39          if(select && select.options && select.options.length > 0){
40              select.options.length=0;
41              var element= document.createElement("option");
42              element.textContent= "Select Environment";
43              element.selected=true;
44              element.disabled=true;
45              element.className="combo-option-text";
46              select.appendChild(element);
47           }else{  select=[];   }
48
49            $.ajax({
50                    type: 'GET',
51                    url:  '/distributor/distribution-targets',
52                    dataType: 'json',
53                    contentType: 'application/json',
54                    success: function(data){
55                     if(data){
56                            for(var i=0; i < data.distributionTargets.length; i++){
57                              var opt= data.distributionTargets[i];
58                              var element= document.createElement("option");
59                               element.textContent= opt.name;
60                               element.value= opt.id;
61                               element.className="combo-option-text";
62                               select.appendChild(element);
63                            }
64                     }
65                   }
66            })
67     }
68
69     /**
70     * @desc: submit button functionality to distribute/POST process group to the environment.
71     */
72      var distributeGraph = function(){
73         var selected_id = $('#operation-context-id').text();
74         // process group id (nifi api) != flow id (nifi registry api)
75         // so must first fetch the flow id from nifi api
76         $.ajax({
77           type: 'GET',
78           url: '../nifi-api/process-groups/'+selected_id,
79           contentType: 'application/json',
80           success: function(data) {
81             const flow_id = data["component"]["versionControlInformation"]["flowId"];
82             const request = {"processGroupId": flow_id}
83
84             $.ajax({
85                     type: 'POST',
86                     data: JSON.stringify(request),
87                     url:  '/distributor/distribution-targets/'+dt_id+'/process-groups',
88                     dataType: 'json',
89                     contentType: 'application/json',
90                     success: function(data){
91                          alert("Success, Your flow have been distributed successfully");
92                     },
93                     error: function(err) {
94                         alert("Issue with distribution:\n\n" + JSON.stringify(err, null, 2));
95                     }
96             });
97           }
98         })
99      };
100
101
102    /**
103    * @desc: selection of distribution target environment to post the process group
104    */
105    var onEnvironmentSelect = function(){
106      dt_id = $('#environmentType').val();
107      console.log(dt_id);
108      if(dt_id == null){   $('#operate-submit-btn').prop('disabled', true);   }
109      else{  $('#operate-submit-btn').prop('disabled', false);      }
110     };
111
112
113     /**
114     * @desc: event handler for Refresh icon in Operate panel :  invokes api to refresh the list of Envs
115     */
116     var refreshEnvironments= function(){    getDistributionTargets();    };
117
118
119     /**
120     * @desc: event handler for Close icon of Setting/ Distribution Env CRUD dialog :  invokes api to refresh the list of Envs
121     */
122     var onCloseSettings= function(){  getDistributionTargets();  };
123
124
125 function uecvalue(n) {
126   return encodeURIComponent("" + $(n).val());
127 }
128
129 function esc(s) {
130   return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
131 }
132
133 function onBoard() {
134   $("#onboarding-in-progress").show();
135   var url = "/acumos-adapter/onboard.js?acumos=" + uecvalue("#furl");
136   if ($("#cat-menu").val() != "*") {
137     url += "&catalogId=" + uecvalue("#cat-menu");
138     if ($("#sol-menu").val() != "*") {
139       url += "&solutionId=" + uecvalue("#sol-menu");
140       if ($("#rev-menu").val() != "*") {
141         url += "&revisionId=" + uecvalue("#rev-menu");
142       }
143     }
144   }
145   var xhr = new XMLHttpRequest();
146   xhr.onerror = function() {
147     $("#onboarding-in-progress").hide();
148     alert("Onboarding failed");
149   }
150   xhr.onload = function() {
151     if (this.status < 400) {
152       $("#onboarding-in-progress").hide();
153       alert("Onboarding successful");
154     } else {
155       alert("Onboarding error: " + this.statusText);
156     }
157   }
158   xhr.open("POST", url);
159   xhr.send();
160 }
161
162 function chooseSolution() {
163   if ($("#sol-menu").val() == "*") {
164     _updatevis();
165   } else {
166     lookupItem("#ac-revs", "#rev-menu", "/acumos-adapter/listRevisions.js?acumos=" + uecvalue("#furl") + "&solutionId=" + uecvalue("#sol-menu"));
167   }
168 }
169
170 function chooseCatalog() {
171   if ($("#cat-menu").val() == "*") {
172     _updatevis();
173   } else {
174     lookupItem("#ac-sols", "#sol-menu", "/acumos-adapter/listSolutions.js?acumos=" + uecvalue("#furl") + "&catalogId=" + uecvalue("#cat-menu"));
175   }
176 }
177
178 function lookupCatalogs() {
179   $("#onboard").show();
180   lookupItem("#c-acumos", "#cat-menu", "/acumos-adapter/listCatalogs.js?acumos=" + uecvalue("#furl"));
181 }
182
183 function lookupItem(dblock, smenu, url) {
184   var xhr = new XMLHttpRequest();
185   var xmenu = $(smenu);
186   xmenu[0].options.length = 1;
187   xmenu.val("*");
188   xhr.onerror = function() {
189     alert("Error querying remote Acumos system");
190     $(dblock).hide();
191   }
192   xhr.onload = function() {
193     var xresp = JSON.parse(this.response);
194     var i;
195     for (i = 0; i < xresp.length; i++) {
196       var option = document.createElement("option");
197       option.text = esc(xresp[i].name);
198       option.value = xresp[i].id;
199       xmenu[0].add(option);
200     }
201     if (xresp.length == 0) {
202       $(dblock).hide();
203     } else {
204       $(dblock).show();
205     }
206     _updatevis();
207   };
208   xhr.open("GET", url);
209   xhr.send();
210 }
211
212 function setModelType() {
213   if ($("#model-type").val() == "mtAcumos") {
214     $("#furl").val("");
215     $("#mt-acumos").show();
216   }
217   _updatevis();
218 }
219
220 function _updatevis() {
221   if ($("#model-type").val() != "mtAcumos") {
222     $("#mt-acumos").hide();
223     $("#furl").val("");
224   }
225   if ($("#furl").val() == "") {
226     $("#c-acumos").hide();
227     $("#onboard").hide();
228     $("#cat-menu").val("*");
229   }
230   if ($("#cat-menu").val() == "*") {
231     $("#ac-sols").hide();
232     $("#sol-menu").val("");
233   }
234   if ($("#sol-menu").val() == "*") {
235     $("#ac-revs").hide();
236     $("#rev-menu").val("");
237   }
238 }
239
240 function onBoardComponent() {
241   _onBoardFile("#cspec", "/onboarding/components");
242 }
243
244 function onBoardDataFormat() {
245   _onBoardFile("#dfspec", "/onboarding/dataformats");
246 }
247
248 function _onBoardFile(source, url) {
249   reader = new FileReader();
250   reader.onerror = function() {
251     alert("Error reading file");
252   }
253   reader.onload = function(evt) {
254     xhr = new XMLHttpRequest();
255     xhr.onload = function() {
256       if (this.status >= 400) {
257         alert("File upload failed " + this.statusText);
258       } else {
259         alert("File upload complete");
260       }
261     }
262     xhr.onerror = function() {
263       alert("File upload failed");
264     }
265     xhr.open("POST", url);
266     xhr.overrideMimeType("application/json");
267     xhr.send(evt.target.result);
268   };
269   reader.readAsBinaryString($(source)[0].files[0]);
270 }