8a9f9459c1d6c096eae8cabf9604e62a808ac168
[appc/cdt.git] / src / app / shared / services / utilityService / utility.service.ts
1 /*
2 ============LICENSE_START==========================================
3 ===================================================================
4 Copyright (C) 2018 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 ECOMP is a trademark and service mark of AT&T Intellectual Property.
22 ============LICENSE_END============================================
23 */
24
25
26 import {Injectable} from '@angular/core';
27 import {NotificationsService} from 'angular2-notifications';
28 import { saveAs } from 'file-saver';
29 import { appConstants } from '../../../../constants/app-constants';
30
31 @Injectable()
32 export class UtilityService {
33     clName= "UtilityService";
34     public putAction = appConstants.messages.artifactUploadAction;
35     public getAction = appConstants.messages.artifactgetAction;
36     private retrievalSuccessMessage = appConstants.messages.retrievalSuccessMessage;
37     private retrievalFailureMessage = appConstants.messages.retrievalFailureMessage;
38     private saveSuccessMessage = appConstants.messages.saveSuccessMessage;
39     private saveFailureMessage = appConstants.messages.saveFailureMessage;
40     public connectionErrorMessage = appConstants.errors.connectionError;
41     
42     private successMessage = appConstants.messages.artifactRetrivalsuccessMessage;
43     private failureMessage = appConstants.messages.artifactRetrivalfailureMessage;
44
45     constructor(private notificationService: NotificationsService) {
46     }
47
48     public setTracelvl( tlvl: number ) {
49      // console.log( this.clName+": setTracelvl: arg="+tlvl );
50       let tracelvl= tlvl;
51       if( tracelvl == null || tracelvl == undefined ) tracelvl= 0;
52       localStorage["Tracelvl"]= tracelvl;
53     }
54
55     public getTracelvl() : number {
56       let tracelvl= localStorage["Tracelvl"];
57      // console.log( this.clName+": getTracelvl: locS: tracelvl="+tracelvl );
58       if( tracelvl == null || tracelvl == undefined ) {
59         tracelvl=0; localStorage["Tracelvl"]= tracelvl;
60       };
61      // console.log( this.clName+": getTracelvl: tracelvl="+tracelvl );
62       return tracelvl;
63     };
64
65     public randomId() {
66         let x = (new Date().getUTCMilliseconds()) * Math.random();
67         return (x + '').substr(4, 12);
68
69
70     }
71
72     public appendSlashes(artifactData) {
73         return artifactData.replace(/"/g, '\\"');
74     }
75
76     public checkResult(result: any) {
77
78         if (result.output.status.code == appConstants.errorCode["401"]) {
79             this.notificationService.info(appConstants.notifications.titles.information, this.failureMessage);
80             return false;
81         }
82         else if (result.output.status.code == appConstants.errorCode["400"]) {
83             this.notificationService.success(appConstants.notifications.titles.success, this.successMessage);
84             return true;
85         }
86
87     }
88
89     public processApiSubscribe(result: any, action, artifactType) {
90
91         if (result.output.status.code == appConstants.errorCode["401"] && action == this.getAction) {
92             this.notificationService.info(appConstants.notifications.titles.information, this.retrievalFailureMessage);
93         }
94         else if (result.output.status.code == appConstants.errorCode["400"] && action == this.getAction) {
95             this.notificationService.success(appConstants.notifications.titles.success, this.retrievalSuccessMessage);
96         }
97         if (result.output.status.code == appConstants.errorCode["401"] && action == this.putAction) {
98             this.notificationService.warn(appConstants.notifications.titles.error, this.saveFailureMessage + artifactType);
99         }
100         else if (result.output.status.code == appConstants.errorCode["400"] && action == this.putAction) {
101             this.notificationService.success(appConstants.notifications.titles.success, this.saveSuccessMessage + artifactType);
102         }
103
104     }
105
106     public processApiError()
107     {
108         this.notificationService.error(appConstants.notifications.titles.error, this.connectionErrorMessage);
109     }
110
111
112     public checkNotNull(object:any)
113     {
114
115         if (object != undefined || object != null)
116           {
117               if(object.length > 0)
118               return true;
119               else return false;
120           }    
121           else return false;
122     }
123
124     public createPayLoadForSave(artifactType,vnfType,action,fileName, versionNo, artifactContent)
125     {
126         let userId=localStorage['userId'];
127         let apiToken=localStorage['apiToken']
128         let newPayload:any;
129         switch(artifactType)
130         {
131         case "reference_data": 
132         //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 + '"}';
133         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 + '"}';
134         break;
135         case "template_data": 
136         newPayload= JSON.stringify({
137             "userID": userId,
138             "vnf-type": vnfType,
139             "action": action,
140             "artifact-name": fileName,
141             "artifact-type": "APPC-CONFIG",
142             "artifact-version": versionNo,
143             "artifact-contents": artifactContent.replace(/\(([^()]|(R))*\)=\(/g, '').replace(/\)}/g, '}')
144         }); 
145         break;
146         case "param_data": 
147         newPayload=JSON.stringify({
148             "userID": userId,
149             "vnf-type": vnfType,
150             "action": action,
151             "artifact-name": fileName,
152             "artifact-type": "APPC-CONFIG",
153             "artifact-version": versionNo,
154             "artifact-contents": artifactContent
155           }); 
156         break;
157         case "pd_data": 
158         newPayload='{"userID": "' + userId + '","vnf-type" : "' + vnfType + '","action" : "' + action + '","artifact-name" : "' + fileName + '","artifact-type" : "APPC-CONFIG","artifact-version" :"'+versionNo+'","artifact-contents" : ' + artifactContent + '}';
159         break;
160           default : newPayload={};
161         }
162
163         let data =
164           {
165             "input": {
166               "design-request": {
167                 "request-id": apiToken,
168                 "action": "uploadArtifact",
169                 "payload": newPayload
170
171               }
172             }
173           }
174           return data;
175     }
176
177     public createPayloadForRetrieve(isReference:boolean,action,vnfType,fileName)
178     {
179         let payload:any;
180         if(isReference) {
181             payload=JSON.parse(sessionStorage.getItem('updateParams'));
182             payload['userID'] = localStorage['userId'];
183             payload = JSON.stringify(payload);
184         }
185         else payload = '{"userID": "' + localStorage['userId'] + '","action": "' + action + '", "vnf-type" : "' + vnfType + '", "artifact-type":"APPC-CONFIG", "artifact-name":"' + fileName + '"}';
186         let data = {
187                 'input': {
188                     'design-request': {
189                         'request-id': localStorage['apiToken'],
190                         'action': 'getArtifact',
191                         'payload': payload
192                     }
193                 }
194             };
195         return data;    
196     }
197
198     public downloadArtifactToPc(data,extension, fileName, delay)
199     {
200         var blob = new Blob([data], {
201                 type: 'text/'+extension
202             });
203         setTimeout(() => {
204             saveAs(blob, fileName);
205         }, delay)
206     }
207
208 }