1 package org.jmux.app.component;
2
3 import org.jmux.app.App;
4 import org.jmux.app.component.config.Config;
5 import org.mortbay.jetty.Server;
6 import org.mortbay.jetty.servlet.Context;
7
8 import javax.servlet.Servlet;
9 import javax.servlet.http.HttpServlet;
10 import javax.servlet.http.HttpServletRequest;
11 import javax.servlet.http.HttpServletResponse;
12 import java.io.IOException;
13 import java.io.PrintWriter;
14 import java.util.Date;
15 import java.util.HashMap;
16 import java.util.Map;
17
18 /******************************************************************************
19 jmux - Java Modules Using XML
20 Copyright © 2006 jmux.org
21
22 This library is free software; you can redistribute it and/or
23 modify it under the terms of the GNU Lesser General Public
24 License as published by the Free Software Foundation; either
25 version 2.1 of the License, or (at your option) any later version.
26
27 This library is distributed in the hope that it will be useful,
28 but WITHOUT ANY WARRANTY; without even the implied warranty of
29 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
30 Lesser General Public License for more details.
31
32 You should have received a copy of the GNU Lesser General Public
33 License along with this library; if not, write to the Free Software
34 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
35 *****************************************************************************/
36
37 /***
38 * @author donaldw
39 */
40 public class JettyControl extends AbstractControl {
41
42 private Server server;
43 private Context root;
44 private Map<Class<? extends Servlet>, String> servlets = new HashMap<Class<? extends Servlet>, String>();
45
46 public void configure(Config config, App app) {
47 super.configure(config, app);
48
49 this.addServlet(HelloServlet.class, "/*");
50 }
51
52 public void start() {
53 server = new Server(8080);
54 root = new Context(server, "/", Context.SESSIONS);
55
56 for (Map.Entry entry : servlets.entrySet()) {
57 root.addServlet((Class) entry.getKey(), (String) entry.getValue());
58 }
59
60 try {
61 server.start();
62 } catch (Exception ex) {
63 logError("Error starting Jetty", ex);
64 }
65 }
66
67 public void stop() {
68 if (server != null) {
69 if (server.isRunning() || server.isStarting() || server.isStarted()) {
70 try {
71 server.stop();
72 server = null;
73 root = null;
74 } catch (Exception ex) {
75 logError("Error stopping Jetty", ex);
76 }
77 }
78 }
79 }
80
81 public Context getRoot() {
82 return root;
83 }
84
85 public void addServlet(Class<? extends Servlet> aClass, String location) {
86 servlets.put(aClass, location);
87 }
88
89 public static class HelloServlet extends HttpServlet {
90 protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
91 throws IOException {
92 PrintWriter printWriter = httpServletResponse.getWriter();
93 printWriter.println("Hello world!: " + new Date());
94 }
95 }
96 }