001/* 002 * Copyright 2002-2018 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * https://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.springframework.web.socket.server.support; 018 019import javax.servlet.ServletContext; 020 021import org.springframework.context.Lifecycle; 022import org.springframework.context.SmartLifecycle; 023import org.springframework.web.context.ServletContextAware; 024import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping; 025 026/** 027 * An extension of {@link SimpleUrlHandlerMapping} that is also a 028 * {@link SmartLifecycle} container and propagates start and stop calls to any 029 * handlers that implement {@link Lifecycle}. The handlers are typically expected 030 * to be {@code WebSocketHttpRequestHandler} or {@code SockJsHttpRequestHandler}. 031 * 032 * @author Rossen Stoyanchev 033 * @since 4.2 034 */ 035public class WebSocketHandlerMapping extends SimpleUrlHandlerMapping implements SmartLifecycle { 036 037 private volatile boolean running = false; 038 039 040 @Override 041 protected void initServletContext(ServletContext servletContext) { 042 for (Object handler : getUrlMap().values()) { 043 if (handler instanceof ServletContextAware) { 044 ((ServletContextAware) handler).setServletContext(servletContext); 045 } 046 } 047 } 048 049 050 @Override 051 public boolean isAutoStartup() { 052 return true; 053 } 054 055 @Override 056 public int getPhase() { 057 return Integer.MAX_VALUE; 058 } 059 060 @Override 061 public void start() { 062 if (!isRunning()) { 063 this.running = true; 064 for (Object handler : getUrlMap().values()) { 065 if (handler instanceof Lifecycle) { 066 ((Lifecycle) handler).start(); 067 } 068 } 069 } 070 } 071 072 @Override 073 public void stop() { 074 if (isRunning()) { 075 this.running = false; 076 for (Object handler : getUrlMap().values()) { 077 if (handler instanceof Lifecycle) { 078 ((Lifecycle) handler).stop(); 079 } 080 } 081 } 082 } 083 084 @Override 085 public void stop(Runnable callback) { 086 stop(); 087 callback.run(); 088 } 089 090 @Override 091 public boolean isRunning() { 092 return this.running; 093 } 094 095}