View Javadoc

1   /* (c) Copyright 2003 Caleigo AB, All rights reserved. 
2    * 
3    * This library is free software; you can redistribute it and/or
4    * modify it under the terms of the GNU Lesser General Public
5    * License as published by the Free Software Foundation; either
6    * version 2.1 of the License, or (at your option) any later version.
7    * 
8    * This library is distributed in the hope that it will be useful,
9    * but WITHOUT ANY WARRANTY; without even the implied warranty of
10   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11   * Lesser General Public License for more details.
12   * 
13   * You should have received a copy of the GNU Lesser General Public
14   * License along with this library; if not, write to the Free Software
15   * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16   *  
17   */
18  
19  package org.caleigo.toolkit.tunnel;
20  
21  
22  import java.io.*;
23  import javax.servlet.*;
24  import javax.servlet.http.*;
25  
26  import org.caleigo.service.*;
27  import org.caleigo.toolkit.log.*;
28  
29  /***
30   *
31   * @author  Mattias Hagstrand
32   * @version 1.00
33   * 
34   *//* 
35   *
36   * WHEN        WHO               WHY & WHAT
37   * -----------------------------------------------------------------------------
38   * 2002-07-23  Mattias Hagstrand Creation
39   */
40  public abstract class HTTPTunnelServlet extends HttpServlet
41  {
42      // Data members ------------------------------------------------------------
43      protected HTTPTunnelServer mHTTPTunnelServer;
44      
45      /*** Initializes the servlet.
46       */
47      public void init() throws ServletException
48      {
49          Log.print(this, "Initializing...");
50          
51          try
52          {
53              mHTTPTunnelServer = new HTTPTunnelServer();
54              mHTTPTunnelServer.initialize();
55              IService[] services = this.getServices();
56              for (int i = 0; i < services.length; i++)
57                  ServiceProvider.getInstance().addService(services[i]);
58              ServiceProviderServer.getInstance().addTunnelServer(mHTTPTunnelServer);
59          }
60          catch (TunnelException te)
61          {
62              Log.printError(this, "Couldn't initialize http tunnel server", te);
63              throw new ServletException(te.getMessage());
64          }
65          
66          Log.print(this, "done!");
67      }
68      
69      /*** Destroys the servlet.
70       */
71      public void destroy()
72      {
73      }
74          
75      /*** Handles the HTTP <code>GET</code> method.
76       * @param request servlet request
77       * @param response servlet response
78       */
79      protected void doGet(HttpServletRequest request, HttpServletResponse response)
80          throws ServletException, java.io.IOException
81      {
82          response.getOutputStream().println("<html><head><title>HTTPTunnelServer</title></head><body>");
83          response.getOutputStream().println("<h3>" + this.getDescription() + " up and running!</h3>");
84          response.getOutputStream().println("<p>Number of open connections: " + mHTTPTunnelServer.getTunnelCount() + "</p></body></html>");
85          response.getOutputStream().close();
86      }
87      
88      /*** Handles the HTTP <code>POST</code> method.
89       * @param request servlet request
90       * @param response servlet response
91       */
92      protected void doPost(HttpServletRequest request, HttpServletResponse response)
93          throws ServletException, java.io.IOException
94      {
95          try
96          {
97              ObjectInputStream objectInputStream = new ObjectInputStream(request.getInputStream());
98              Object inDataObject = objectInputStream.readObject();
99              
100             if (inDataObject instanceof AbstractTunnel.IConnectionMessage)
101             {
102                 Log.print(this, "Connection message received: " + inDataObject);
103                 // Tell the HTTPTunnelServer to set up a new connection
104                 int sessionID = mHTTPTunnelServer.createSessionID();
105                 mHTTPTunnelServer.newConnection(inDataObject, response.getOutputStream(), sessionID);
106                 Log.print(this, "Connection closed");
107             }
108             else if (inDataObject instanceof HTTPTunnel.HTTPTunnelPackage)
109             {
110 //                if (((HTTPTunnel.HTTPTunnelPackage) inDataObject).getMessage() instanceof HTTPTunnel.HTTPTunnelCloseMessage)
111 //                    mHTTPTunnelServer.closeConnection(((HTTPTunnel.HTTPTunnelPackage) inDataObject).getSessionID());
112                 if(((HTTPTunnel.HTTPTunnelPackage) inDataObject).getMessage() instanceof byte[])
113                     mHTTPTunnelServer.handleInputData(((HTTPTunnel.HTTPTunnelPackage) inDataObject).getSessionID(),
114                                                       (byte[]) ((HTTPTunnel.HTTPTunnelPackage) inDataObject).getMessage());
115                 else
116                     Log.printWarning(this, "Unknown message format");
117             }
118         }
119         catch (Exception e)
120         {
121             Log.printError(this, "Error while handling post message", e);
122             response.getOutputStream().close();
123         }
124     }
125     
126     /*** Returns a short description of the servlet.
127      */
128     public String getServletInfo()
129     {
130         return this.getDescription();
131     }
132     
133     // Abstract methods --------------------------------------------------------
134     protected abstract String getDescription();
135     protected abstract IService[] getServices();
136     
137     // Help methods ------------------------------------------------------------
138     
139     /*** Help method that returns the root path to where the application
140      * is started from. If the application was started as a jar application
141      * the system path to that jar is returned. If the the application was
142      * started as a class file structure the system path to the root/default
143      * package is returned.
144      * 
145      * @return The root path with at trailing '/' or null if the path could
146      *          not be calculated.
147      */
148     public String getApplicationRootPath()
149     {
150         // Get resource url to current class.
151         String className = this.getClass().getName().replace('.', '/')+".class";
152         java.net.URL url = this.getClass().getClassLoader().getResource(className);
153         if(url==null)
154             return null;
155             
156         // Extract path name resource url
157         String path = url.getPath();
158         path = path.replaceAll("//Q%20//E", " ");
159         if(path.indexOf("!")>=0)
160         {
161             path = path.substring(path.indexOf('/'), path.indexOf("!"));
162             path = path.substring(0, path.lastIndexOf('/')+1);
163         }
164         else if(path.endsWith(className))
165             path = path.substring(0, path.length()-className.length());
166         else
167             path = null;
168         return path;
169     }
170 }