[SDC] rebase 1710 code
[sdc.git] / catalog-ui / src / app / ng2 / services / http.interceptor.service.ts
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 import 'rxjs/add/operator/map';
22 import 'rxjs/add/operator/toPromise';
23 import 'rxjs/Rx';
24 import {sdc2Config} from './../../../main';
25 import {Interceptor, InterceptedRequest, InterceptedResponse} from 'ng2-interceptors';
26 import {SharingService} from "../../services/sharing-service";
27 import {ReflectiveInjector} from '@angular/core';
28 import {Cookie2Service} from "./cookie.service";
29 import {UUID} from "angular2-uuid";
30 import {Dictionary} from "../../utils/dictionary/dictionary";
31 import {SEVERITY} from "../../utils/constants";
32 import {IServerMessageModalModel} from "../../view-models/modals/message-modal/message-server-modal/server-message-modal-view-model";
33
34
35 export class HttpInterceptor implements Interceptor {
36
37     private cookieService:Cookie2Service;
38     private sharingService:SharingService;
39
40     constructor() {
41         let injector = ReflectiveInjector.resolveAndCreate([Cookie2Service, SharingService]);
42         this.cookieService = injector.get(Cookie2Service);
43         this.sharingService = injector.get(SharingService);
44     }
45
46     public interceptBefore(request:InterceptedRequest):InterceptedRequest {
47         /**
48          * For every request to the server, that the service id, or resource id is sent in the URL, need to pass UUID in the header.
49          * Check if the unique id exists in uuidMap, and if so get the UUID and add it to the header.
50          */
51         request.options.headers.append(this.cookieService.getUserIdSuffix(), this.cookieService.getUserId());
52         request.options.withCredentials = true;
53         var uuidValue = this.getUuidValue(request.url);
54         if (uuidValue != '') {
55             request.options.headers.set('X-ECOMP-ServiceID', uuidValue);
56         }
57         request.options.headers.set('X-ECOMP-RequestID', UUID.UUID());
58         return request;
59     }
60
61     public interceptAfter(response:InterceptedResponse):InterceptedResponse {
62
63         if (response.response.status !== 200 && response.response.status !== 201) {
64             this.responseError(response.response.json());
65             //console.log("Error from BE:",response);
66         }
67         return response;
68     }
69
70     private getUuidValue = (url:string):string => {
71         let map:Dictionary<string, string> = this.sharingService.getUuidMap();
72         if (map && url.indexOf(sdc2Config.api.root) > 0) {
73             map.forEach((key:string) => {
74                 if (url.indexOf(key) !== -1) {
75                     return this.sharingService.getUuidValue(key);
76                 }
77             });
78         }
79         return '';
80     };
81
82     public formatMessageArrays = (message:string, variables:Array<string>)=> {
83         return message.replace(/\[%(\d+)\]/g, function (_, m) {
84             let tmp = [];
85             let list = variables[--m].split(";");
86             list.forEach(function (item) {
87                 tmp.push("<li>" + item + "</li>");
88             });
89             return "<ul>" + tmp.join("") + "</ul>";
90         });
91     };
92
93     public responseError = (rejection:any)=> {
94
95         let text:string;
96         let variables;
97         let messageId:string = "";
98         let isKnownException = false;
99
100         if (rejection && rejection.serviceException) {
101             text = rejection.serviceException.text;
102             variables = rejection.serviceException.variables;
103             messageId = rejection.serviceException.messageId;
104             isKnownException = true;
105         } else if (rejection && rejection.requestError && rejection.requestError.serviceException) {
106             text = rejection.requestError.serviceException.text;
107             variables = rejection.requestError.serviceException.variables;
108             messageId = rejection.requestError.serviceException.messageId;
109             isKnownException = true;
110         } else if (rejection && rejection.requestError && rejection.requestError.policyException) {
111             text = rejection.requestError.policyException.text;
112             variables = rejection.requestError.policyException.variables;
113             messageId = rejection.requestError.policyException.messageId;
114             isKnownException = true;
115         } else if (rejection) {
116             text = 'Wrong error format from server';
117             console.error(text);
118             isKnownException = false;
119         }
120
121         let data:IServerMessageModalModel;
122         if (isKnownException) {
123             // Remove the "Error: " text at the begining
124             if (text.trim().indexOf("Error:") === 0) {
125                 text = text.replace("Error:", "").trim();
126             }
127
128             //mshitrit DE199895 bug fix
129             let count:number = 0;
130             variables.forEach(function (item) {
131                 variables[count] = item ? item.replace('<', '&lt').replace('>', '&gt') : '';
132                 count++;
133             });
134
135             // Format the message in case has array to <ul><li>
136             text = this.formatMessageArrays(text, variables);
137
138             // Format the message %1 %2
139             text = text.format(variables);
140
141             // Need to inject the MessageService manually to prevent circular dependencies (because MessageService use $templateCache that use $http).
142             data = {
143                 title: 'Error',
144                 message: text,
145                 messageId: messageId,
146                 status: rejection.status,
147                 severity: SEVERITY.ERROR
148             };
149         } else {
150             // Need to inject the MessageService manually to prevent circular dependencies (because MessageService use $templateCache that use $http).
151             data = {
152                 title: 'Error',
153                 message: rejection.status !== -1 ? rejection.statusText : "Error getting response from server",
154                 messageId: messageId,
155                 status: rejection.status,
156                 severity: SEVERITY.ERROR
157             };
158         }
159
160         console.error('ERROR data',data);
161     }
162 }