a683f33c01f74f3d8add70604be3fba81cbcfdf6
[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     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 randomId() {
48         let x = (new Date().getUTCMilliseconds()) * Math.random();
49         return (x + '').substr(4, 12);
50
51
52     }
53
54     public appendSlashes(artifactData) {
55         return artifactData.replace(/"/g, '\\"');
56     }
57
58     public checkResult(result: any) {
59
60         if (result.output.status.code == appConstants.errorCode["401"]) {
61             this.notificationService.info(appConstants.notifications.titles.information, this.failureMessage);
62             return false;
63         }
64         else if (result.output.status.code == appConstants.errorCode["400"]) {
65             this.notificationService.success(appConstants.notifications.titles.success, this.successMessage);
66             return true;
67         }
68
69     }
70
71     public processApiSubscribe(result: any, action, artifactType) {
72
73         if (result.output.status.code == appConstants.errorCode["401"] && action == this.getAction) {
74             this.notificationService.info(appConstants.notifications.titles.information, this.retrievalFailureMessage);
75         }
76         else if (result.output.status.code == appConstants.errorCode["400"] && action == this.getAction) {
77             this.notificationService.success(appConstants.notifications.titles.success, this.retrievalSuccessMessage);
78         }
79         if (result.output.status.code == appConstants.errorCode["401"] && action == this.putAction) {
80             this.notificationService.warn(appConstants.notifications.titles.error, this.saveFailureMessage + artifactType);
81         }
82         else if (result.output.status.code == appConstants.errorCode["400"] && action == this.putAction) {
83             this.notificationService.success(appConstants.notifications.titles.success, this.saveSuccessMessage + artifactType);
84         }
85
86     }
87
88     public processApiError()
89     {
90         this.notificationService.error(appConstants.notifications.titles.error, this.connectionErrorMessage);
91     }
92
93
94     public checkNotNull(object:any)
95     {
96
97         if (object != undefined || object != null)
98           {
99               if(object.length > 0)
100               return true;
101               else return false;
102           }    
103           else return false;
104     }
105
106     public createPayLoadForSave(artifactType,vnfType,action,fileName, versionNo, artifactContent)
107     {
108         let userId=localStorage['userId'];
109         let apiToken=localStorage['apiToken']
110         let newPayload:any;
111         switch(artifactType)
112         {
113         case "reference_data": 
114         //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 + '"}';
115         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 + '"}';
116         break;
117         case "template_data": 
118         newPayload= JSON.stringify({
119             "userID": userId,
120             "vnf-type": vnfType,
121             "action": action,
122             "artifact-name": fileName,
123             "artifact-type": "APPC-CONFIG",
124             "artifact-version": versionNo,
125             "artifact-contents": artifactContent.replace(/\(([^()]|(R))*\)=\(/g, '').replace(/\)}/g, '}')
126         }); 
127         break;
128         case "param_data": 
129         newPayload=JSON.stringify({
130             "userID": userId,
131             "vnf-type": vnfType,
132             "action": action,
133             "artifact-name": fileName,
134             "artifact-type": "APPC-CONFIG",
135             "artifact-version": versionNo,
136             "artifact-contents": artifactContent
137           }); 
138         break;
139         case "pd_data": 
140         newPayload='{"userID": "' + userId + '","vnf-type" : "' + vnfType + '","action" : "' + action + '","artifact-name" : "' + fileName + '","artifact-type" : "APPC-CONFIG","artifact-version" :"'+versionNo+'","artifact-contents" : ' + artifactContent + '}';
141         break;
142           default : newPayload={};
143         }
144
145         let data =
146           {
147             "input": {
148               "design-request": {
149                 "request-id": apiToken,
150                 "action": "uploadArtifact",
151                 "payload": newPayload
152
153               }
154             }
155           }
156           return data;
157     }
158
159     public createPayloadForRetrieve(isReference:boolean,action,vnfType,fileName)
160     {
161         let payload:any;
162         if(isReference) {
163             payload=JSON.parse(sessionStorage.getItem('updateParams'));
164             payload['userID'] = localStorage['userId'];
165             payload = JSON.stringify(payload);
166         }
167         else payload = '{"userID": "' + localStorage['userId'] + '","action": "' + action + '", "vnf-type" : "' + vnfType + '", "artifact-type":"APPC-CONFIG", "artifact-name":"' + fileName + '"}';
168         let data = {
169                 'input': {
170                     'design-request': {
171                         'request-id': localStorage['apiToken'],
172                         'action': 'getArtifact',
173                         'payload': payload
174                     }
175                 }
176             };
177         return data;    
178     }
179
180     public downloadArtifactToPc(data,extension, fileName, delay)
181     {
182         var blob = new Blob([data], {
183                 type: 'text/'+extension
184             });
185         setTimeout(() => {
186             saveAs(blob, fileName);
187         }, delay)
188     }
189
190 }