blob: 4ccf9ea255c810a933a2a0f2ce2350b7a8a8ac91 [file] [log] [blame]
Thomas Vachuska3553b302015-03-07 14:49:43 -08001/*
2 * Copyright 2015 Open Networking Laboratory
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 */
16package org.onosproject.ui.impl;
17
18import org.eclipse.jetty.websocket.WebSocket;
19import org.eclipse.jetty.websocket.WebSocketServlet;
20import org.onlab.osgi.DefaultServiceDirectory;
21import org.onlab.osgi.ServiceDirectory;
22
23import javax.servlet.ServletException;
24import javax.servlet.http.HttpServletRequest;
25import java.util.HashSet;
26import java.util.Iterator;
27import java.util.Set;
28import java.util.Timer;
29import java.util.TimerTask;
30
31/**
32 * Web socket servlet capable of creating web sockets for the user interface.
33 */
34public class UiWebSocketServlet extends WebSocketServlet {
35
36 private static final long PING_DELAY_MS = 5000;
37
Thomas Vachuska51f540f2015-05-27 17:26:57 -070038 private static UiWebSocketServlet instance;
39
Thomas Vachuska3553b302015-03-07 14:49:43 -080040 private ServiceDirectory directory = new DefaultServiceDirectory();
41
42 private final Set<UiWebSocket> sockets = new HashSet<>();
43 private final Timer timer = new Timer();
44 private final TimerTask pruner = new Pruner();
45
Thomas Vachuska51f540f2015-05-27 17:26:57 -070046 /**
47 * Closes all currently open UI web-sockets.
48 */
49 public static void closeAll() {
50 if (instance != null) {
51 instance.sockets.forEach(UiWebSocket::close);
52 instance.sockets.clear();
53 }
54 }
55
Thomas Vachuska3553b302015-03-07 14:49:43 -080056 @Override
57 public void init() throws ServletException {
58 super.init();
Thomas Vachuska51f540f2015-05-27 17:26:57 -070059 instance = this;
Thomas Vachuska3553b302015-03-07 14:49:43 -080060 timer.schedule(pruner, PING_DELAY_MS, PING_DELAY_MS);
61 }
62
63 @Override
64 public WebSocket doWebSocketConnect(HttpServletRequest request, String protocol) {
65 UiWebSocket socket = new UiWebSocket(directory);
66 synchronized (sockets) {
67 sockets.add(socket);
68 }
69 return socket;
70 }
71
72 // Task for pruning web-sockets that are idle.
73 private class Pruner extends TimerTask {
74 @Override
75 public void run() {
76 synchronized (sockets) {
77 Iterator<UiWebSocket> it = sockets.iterator();
78 while (it.hasNext()) {
79 UiWebSocket socket = it.next();
80 if (socket.isIdle()) {
81 it.remove();
82 socket.close();
83 }
84 }
85 }
86 }
87 }
88}