View Javadoc
1   /*
2    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
3    * The software in this package is published under the terms of the CPAL v1.0
4    * license, a copy of which has been included with this distribution in the
5    * LICENSE.txt file.
6    */
7   package org.mule.transport.servlet.jetty.util;
8   
9   import org.mule.api.MuleContext;
10  import org.mule.api.config.MuleProperties;
11  
12  import javax.servlet.Servlet;
13  import javax.servlet.ServletContextEvent;
14  import javax.servlet.ServletContextListener;
15  
16  import org.mortbay.jetty.Server;
17  import org.mortbay.jetty.servlet.Context;
18  import org.mortbay.jetty.servlet.ServletHolder;
19  
20  /**
21   * A simple helper class for Mule testing that creates an embedded Jetty Server
22   */
23  public class EmbeddedJettyServer
24  {
25      private Server httpServer;
26  
27      public EmbeddedJettyServer(int port, String contextPath, String servletPath, Servlet servlet, final MuleContext context)
28      {
29           httpServer = new Server(port);
30  
31          Context c = new Context(httpServer, contextPath, Context.SESSIONS);
32          c.addServlet(new ServletHolder(servlet), servletPath);
33          c.addEventListener(new ServletContextListener() {
34              public void contextInitialized(ServletContextEvent sce)
35              {
36                  sce.getServletContext().setAttribute(MuleProperties.MULE_CONTEXT_PROPERTY, context);
37              }
38  
39              public void contextDestroyed(ServletContextEvent sce) { }
40          });
41      }
42  
43      public void start() throws Exception
44      {
45          httpServer.start();
46      }
47  
48      public void stop() throws Exception
49      {
50          httpServer.stop();
51      }
52  
53      public void destroy()
54      {
55          httpServer.destroy();
56      }
57  
58      public boolean isStarted()
59      {
60          return httpServer.isStarted();
61      }
62  }