Authentication support for cdt
[appc/cdt.git] / src / app / shared / services / utilityService / utility.service.ts
1 /*
2 ============LICENSE_START==========================================
3 ===================================================================
4 Copyright (C) 2018-2020 AT&T Intellectual Property. All rights reserved.
5 ===================================================================
6 Copyright (C) 2018 IBM.
7 ===================================================================
8 Unless otherwise specified, all software contained herein is licensed
9 under the Apache License, Version 2.0 (the License);
10 you may not use this software except in compliance with the License.
11 You may obtain a copy of the License at
12
13     http://www.apache.org/licenses/LICENSE-2.0
14
15 Unless required by applicable law or agreed to in writing, software
16 distributed under the License is distributed on an "AS IS" BASIS,
17 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 See the License for the specific language governing permissions and
19 limitations under the License.
20
21 ============LICENSE_END============================================
22 */
23
24
25 import {Injectable} from '@angular/core';
26 import {NotificationsService} from 'angular2-notifications';
27 import { saveAs } from 'file-saver';
28 import { appConstants } from '../../../../constants/app-constants';
29
30 @Injectable()
31 export class UtilityService {
32     clName= "UtilityService";
33     public putAction = appConstants.messages.artifactUploadAction;
34     public getAction = appConstants.messages.artifactgetAction;
35     private retrievalSuccessMessage = appConstants.messages.retrievalSuccessMessage;
36     private retrievalFailureMessage = appConstants.messages.retrievalFailureMessage;
37     private saveSuccessMessage = appConstants.messages.saveSuccessMessage;
38     private saveFailureMessage = appConstants.messages.saveFailureMessage;
39     public connectionErrorMessage = appConstants.errors.connectionError;
40     
41     private successMessage = appConstants.messages.artifactRetrivalsuccessMessage;
42     private failureMessage = appConstants.messages.artifactRetrivalfailureMessage;
43
44     constructor(private notificationService: NotificationsService) {
45     }
46
47     public setTracelvl( tlvl: number ) {
48      // console.log( this.clName+": setTracelvl: arg="+tlvl );
49       let tracelvl= tlvl;
50       if( tracelvl == null || tracelvl == undefined ) tracelvl= 0;
51       localStorage["Tracelvl"]= tracelvl;
52     }
53
54     public getTracelvl() : number {
55       let tracelvl= localStorage["Tracelvl"];
56      // console.log( this.clName+": getTracelvl: locS: tracelvl="+tracelvl );
57       if( tracelvl == null || tracelvl == undefined ) {
58         tracelvl=0; localStorage["Tracelvl"]= tracelvl;
59       };
60      // console.log( this.clName+": getTracelvl: tracelvl="+tracelvl );
61       return tracelvl;
62     };
63
64     public randomId() {
65         let x = (new Date().getUTCMilliseconds()) * Math.random();
66         return (x + '').substr(4, 12);
67
68
69     }
70
71     public appendSlashes(artifactData) {
72         return artifactData.replace(/"/g, '\\"');
73     }
74
75         // get current date in "mm/dd/yyyy"
76     getDate() {
77         let toDay = new Date();
78         return (toDay.getMonth()+1) +"/"+ toDay.getDate() +"/"+ toDay.getFullYear();
79     }
80
81
82
83
84     public checkResult(result: any) {
85
86         if (result.output.status.code == appConstants.errorCode["401"]) {
87             this.notificationService.info(appConstants.notifications.titles.information, this.failureMessage);
88             return false;
89         }
90         else if (result.output.status.code == appConstants.errorCode["400"]) {
91             this.notificationService.success(appConstants.notifications.titles.success, this.successMessage);
92             return true;
93         }
94
95     }
96
97     public processApiSubscribe(result: any, action, artifactType) {
98
99         if (result.output.status.code == appConstants.errorCode["401"] && action == this.getAction) {
100             this.notificationService.info(appConstants.notifications.titles.information, this.retrievalFailureMessage);
101         }
102         else if (result.output.status.code == appConstants.errorCode["400"] && action == this.getAction) {
103             this.notificationService.success(appConstants.notifications.titles.success, this.retrievalSuccessMessage);
104         }
105         if (result.output.status.code == appConstants.errorCode["401"] && action == this.putAction) {
106             this.notificationService.warn(appConstants.notifications.titles.error, this.saveFailureMessage + artifactType);
107         }
108         else if (result.output.status.code == appConstants.errorCode["400"] && action == this.putAction) {
109             this.notificationService.success(appConstants.notifications.titles.success, this.saveSuccessMessage + artifactType);
110         }
111
112     }
113
114     public processApiError()
115     {
116         this.notificationService.error(appConstants.notifications.titles.error, this.connectionErrorMessage);
117     }
118
119
120     public checkNotNull(object:any)
121     {
122
123         if (object != undefined || object != null)
124           {
125               if(object.length > 0)
126               return true;
127               else return false;
128           }    
129           else return false;
130     }
131
132     public createPayLoadForSave(artifactType,vnfType,action,fileName, versionNo, artifactContent)
133     {
134         let userId=sessionStorage['userId'];
135         let apiToken=sessionStorage['apiToken']
136         let newPayload:any;
137         switch(artifactType)
138         {
139         case "reference_data": 
140         //newPayload='{"userID": "' + userId + '","vnf-type" : "' + vnfType + '","action: "'+action+'","artifact-name" : "' + fileName.replace(/ /g, '').replace(new RegExp('/', 'g'), '_').replace(/ /g, '') + '","artifact-type" : "APPC-CONFIG","artifact-version" : "0.1","artifact-contents" :" ' + artifactContent + '"}';
141         newPayload='{"userID": "' + userId + '","vnf-type" : "' + vnfType + '","action" : "AllAction","artifact-name" : "' + fileName.replace(/ /g, '').replace(new RegExp('/', 'g'), '_').replace(/ /g, '') + '","artifact-type" : "APPC-CONFIG","artifact-version" : "0.1","artifact-contents" :" ' + artifactContent + '"}';
142         break;
143         case "template_data": 
144         newPayload= JSON.stringify({
145             "userID": userId,
146             "vnf-type": vnfType,
147             "action": action,
148             "artifact-name": fileName,
149             "artifact-type": "APPC-CONFIG",
150             "artifact-version": versionNo,
151             "artifact-contents": artifactContent.replace(/\(([^()]|(R))*\)=\(/g, '').replace(/\)}/g, '}')
152         }); 
153         break;
154         case "param_data": 
155         newPayload=JSON.stringify({
156             "userID": userId,
157             "vnf-type": vnfType,
158             "action": action,
159             "artifact-name": fileName,
160             "artifact-type": "APPC-CONFIG",
161             "artifact-version": versionNo,
162             "artifact-contents": artifactContent
163           }); 
164         break;
165         case "pd_data": 
166         newPayload='{"userID": "' + userId + '","vnf-type" : "' + vnfType + '","action" : "' + action + '","artifact-name" : "' + fileName + '","artifact-type" : "APPC-CONFIG","artifact-version" :"'+versionNo+'","artifact-contents" : ' + artifactContent + '}';
167         break;
168           default : newPayload={};
169         }
170
171         let data =
172           {
173             "input": {
174               "design-request": {
175                 "request-id": apiToken,
176                 "action": "uploadArtifact",
177                 "payload": newPayload
178
179               }
180             }
181           }
182           return data;
183     }
184
185     public createPayloadForRetrieve(isReference:boolean,action,vnfType,fileName)
186     {
187         let payload:any;
188         if(isReference) {
189             payload=JSON.parse(sessionStorage.getItem('updateParams'));
190             payload['userID'] = sessionStorage['userId'];
191             payload = JSON.stringify(payload);
192         }
193         else payload = '{"userID": "' + sessionStorage['userId'] + '","action": "' + action + '", "vnf-type" : "' + vnfType + '", "artifact-type":"APPC-CONFIG", "artifact-name":"' + fileName + '"}';
194         let data = {
195                 'input': {
196                     'design-request': {
197                         'request-id': sessionStorage['apiToken'],
198                         'action': 'getArtifact',
199                         'payload': payload
200                     }
201                 }
202             };
203         return data;    
204     }
205
206     public downloadArtifactToPc(data,extension, fileName, delay)
207     {
208         var blob = new Blob([data], {
209                 type: 'text/'+extension
210             });
211         setTimeout(() => {
212             saveAs(blob, fileName);
213         }, delay)
214     }
215
216 }