Upgrade jacoco/lombok/sonar versions
[sdc.git] / openecomp-ui / src / nfvo-utils / WebSocketUtil.js
1 /*
2 * Copyright © 2018 European Support Limited
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http: //www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 import store from 'sdc-app/AppStore.js';
18 import Configuration from 'sdc-app/config/Configuration.js';
19 import { actionTypes } from 'sdc-app/onboarding/userNotifications/UserNotificationsConstants.js';
20 import WorkerUtil from 'nfvo-utils/WorkerUtil';
21
22 export const websocketUrl =
23     Configuration.get('websocketProtocol') +
24     '://' +
25     window.location.hostname +
26     ':' +
27     Configuration.get('websocketPort') +
28     '/' +
29     Configuration.get('websocketPath');
30
31 /***
32  * Websocket is treated like a singleton. only need one for the application.
33  */
34 let websocket;
35 const workerUtil = new WorkerUtil();
36 export default {
37     open(url, { lastScanned }) {
38         if (
39             websocket === undefined ||
40             websocket.readyState === websocket.CLOSED
41         ) {
42             websocket = new WebSocket(
43                 `${url}?LAST_DELIVERED_EVENT_ID=${lastScanned}`
44             );
45             websocket.onmessage = event =>
46                 store.dispatch({
47                     type: actionTypes.NOTIFICATION,
48                     data: JSON.parse(event.data)
49                 });
50             websocket.onclose = event => {
51                 if (event.code && event.code === 1001) {
52                     // - Idle Timeout
53                     const { lastScanned } = store.getState().notifications;
54                     console.log('Reconnecting to Websocket');
55                     this.open(websocketUrl, { lastScanned });
56                 }
57             };
58             websocket.onerror = () => {
59                 workerUtil.open();
60             };
61         }
62     },
63
64     close() {
65         if (websocket !== undefined) {
66             websocket.close();
67         }
68
69         workerUtil.close();
70     }
71 };