Thomas Vachuska | 3553b30 | 2015-03-07 14:49:43 -0800 | [diff] [blame] | 1 | /* |
| 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 | */ |
| 16 | package org.onosproject.ui.impl; |
| 17 | |
| 18 | import org.eclipse.jetty.websocket.WebSocket; |
| 19 | import org.eclipse.jetty.websocket.WebSocketServlet; |
| 20 | import org.onlab.osgi.DefaultServiceDirectory; |
| 21 | import org.onlab.osgi.ServiceDirectory; |
| 22 | |
| 23 | import javax.servlet.ServletException; |
| 24 | import javax.servlet.http.HttpServletRequest; |
| 25 | import java.util.HashSet; |
| 26 | import java.util.Iterator; |
| 27 | import java.util.Set; |
| 28 | import java.util.Timer; |
| 29 | import java.util.TimerTask; |
| 30 | |
| 31 | /** |
| 32 | * Web socket servlet capable of creating web sockets for the user interface. |
| 33 | */ |
| 34 | public class UiWebSocketServlet extends WebSocketServlet { |
| 35 | |
| 36 | private static final long PING_DELAY_MS = 5000; |
| 37 | |
| 38 | private ServiceDirectory directory = new DefaultServiceDirectory(); |
| 39 | |
| 40 | private final Set<UiWebSocket> sockets = new HashSet<>(); |
| 41 | private final Timer timer = new Timer(); |
| 42 | private final TimerTask pruner = new Pruner(); |
| 43 | |
| 44 | @Override |
| 45 | public void init() throws ServletException { |
| 46 | super.init(); |
| 47 | timer.schedule(pruner, PING_DELAY_MS, PING_DELAY_MS); |
| 48 | } |
| 49 | |
| 50 | @Override |
| 51 | public WebSocket doWebSocketConnect(HttpServletRequest request, String protocol) { |
| 52 | UiWebSocket socket = new UiWebSocket(directory); |
| 53 | synchronized (sockets) { |
| 54 | sockets.add(socket); |
| 55 | } |
| 56 | return socket; |
| 57 | } |
| 58 | |
| 59 | // Task for pruning web-sockets that are idle. |
| 60 | private class Pruner extends TimerTask { |
| 61 | @Override |
| 62 | public void run() { |
| 63 | synchronized (sockets) { |
| 64 | Iterator<UiWebSocket> it = sockets.iterator(); |
| 65 | while (it.hasNext()) { |
| 66 | UiWebSocket socket = it.next(); |
| 67 | if (socket.isIdle()) { |
| 68 | it.remove(); |
| 69 | socket.close(); |
| 70 | } |
| 71 | } |
| 72 | } |
| 73 | } |
| 74 | } |
| 75 | } |