View Javadoc

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