View Javadoc

1   //
2   //  ========================================================================
3   //  Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
4   //  ------------------------------------------------------------------------
5   //  All rights reserved. This program and the accompanying materials
6   //  are made available under the terms of the Eclipse Public License v1.0
7   //  and Apache License v2.0 which accompanies this distribution.
8   //
9   //      The Eclipse Public License is available at
10  //      http://www.eclipse.org/legal/epl-v10.html
11  //
12  //      The Apache License v2.0 is available at
13  //      http://www.opensource.org/licenses/apache2.0.php
14  //
15  //  You may elect to redistribute this code under either of these licenses.
16  //  ========================================================================
17  //
18  
19  package org.eclipse.jetty.cdi.websocket;
20  
21  import java.util.Set;
22  
23  import javax.servlet.ServletContainerInitializer;
24  import javax.servlet.ServletContext;
25  import javax.servlet.ServletException;
26  
27  import org.eclipse.jetty.server.handler.ContextHandler;
28  import org.eclipse.jetty.servlet.ServletContextHandler;
29  import org.eclipse.jetty.util.component.ContainerLifeCycle;
30  import org.eclipse.jetty.util.thread.ThreadClassLoaderScope;
31  
32  public class WebSocketCdiInitializer implements ServletContainerInitializer
33  {
34      public static void configureContext(ServletContextHandler context) throws ServletException
35      {
36          try (ThreadClassLoaderScope scope = new ThreadClassLoaderScope(context.getClassLoader()))
37          {
38              addListeners(context);
39          }
40      }
41  
42      @Override
43      public void onStartup(Set<Class<?>> c, ServletContext context) throws ServletException
44      {
45          ContextHandler handler = ContextHandler.getContextHandler(context);
46  
47          if (handler == null)
48          {
49              throw new ServletException("Not running on Jetty, WebSocket+CDI support unavailable");
50          }
51  
52          if (!(handler instanceof ServletContextHandler))
53          {
54              throw new ServletException("Not running in Jetty ServletContextHandler, WebSocket+CDI support unavailable");
55          }
56  
57          ServletContextHandler jettyContext = (ServletContextHandler)handler;
58          try (ThreadClassLoaderScope scope = new ThreadClassLoaderScope(context.getClassLoader()))
59          {
60              addListeners(jettyContext);
61          }
62      }
63      
64      private static void addListeners(ContainerLifeCycle container)
65      {
66          WebSocketCdiListener listener = new WebSocketCdiListener();
67          container.addLifeCycleListener(listener);
68          container.addEventListener(listener);
69      }
70  }