KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > mmbase > servlet > JamesServlet


1 /*
2
3 This software is OSI Certified Open Source Software.
4 OSI Certified is a certification mark of the Open Source Initiative.
5
6 The license (Mozilla version 1.0) can be read at the MMBase site.
7 See http://www.MMBase.org/license
8
9 */

10 package org.mmbase.servlet;
11
12 import java.util.*;
13
14 import java.net.InetAddress JavaDoc;
15 import java.net.UnknownHostException JavaDoc;
16
17 import javax.servlet.ServletException JavaDoc;
18 import javax.servlet.http.HttpServletRequest JavaDoc;
19 import javax.servlet.http.HttpServletResponse JavaDoc;
20 import javax.servlet.http.Cookie JavaDoc;
21
22 import org.mmbase.module.core.*;
23 import org.mmbase.util.AuthorizationException;
24 import org.mmbase.util.HttpAuth;
25 import org.mmbase.util.NotLoggedInException;
26
27 import org.mmbase.util.logging.Logger;
28 import org.mmbase.util.logging.Logging;
29
30
31 /**
32  * JamesServlet is a adaptor class.
33  * It is used to extend the basic Servlet to provide services not found in suns Servlet API.
34  *
35  * @dependency this code relies on HttpAuth for its authorization.
36  * This should be done through the MMBase security.
37  * @duplicate this code is aimed at the SCAN servlets, and some features (i.e. cookies) do
38  * not communicate well with jsp pages.
39  * Functionality might need to be moved or adapted so that it uses the MMCI.
40  *
41  * @application SCAN - the cookie code is specific for SCAN
42  * @author vpro
43  * @version $Id: JamesServlet.java,v 1.49 2006/03/09 16:39:03 michiel Exp $
44  */

45
46 public class JamesServlet extends MMBaseServlet {
47     private static final Logger log = Logging.getLoggerInstance(JamesServlet.class);
48     protected static Logger pageLog;
49
50     /**
51      * Initializes the servlet.
52      */

53     public void init() throws ServletException JavaDoc {
54         super.init();
55         // Initializing log here because log4j has to be initialized first.
56
pageLog = Logging.getLoggerInstance(Logging.PAGE_CATEGORY);
57     }
58
59     /**
60      * Retrieves a module.
61      * Creates the module if it hasn't been created yet (but does not initialize).
62      * @todo type returned should be Module
63      * @param name the name of the module to retrieve
64      * @return the {@link org.mmbase.module.Module}, or <code>null</code> if it doesn't exist.
65      */

66     protected final Object JavaDoc getModule(String JavaDoc name) {
67         return org.mmbase.module.Module.getModule(name);
68     }
69
70     /**
71      * Retrieves all initialization parameters.
72      * Note: overides the normal way to set init params in javax.
73      */

74     protected final Hashtable getInitParameters() {
75         return null;
76     }
77
78     /**
79      * Gets properties. If allowed.
80      */

81     protected final Hashtable getProperties(String JavaDoc name) {
82         return null;
83      }
84
85     /**
86      * Gets a property out of the Environment. If allowed
87      */

88     protected final String JavaDoc getProperty(String JavaDoc name, String JavaDoc var) {
89         return null;
90     }
91
92     /**
93      * Try to get the default authorisation
94      * @deprecation-used should call Security, not HttpAuth
95      * @param req The HttpServletRequest.
96      * @param res The HttpServletResponse.
97      * @exception AuthorizationException if the authorization fails.
98      * @exception NotLoggedInException if the user hasn't logged in yet.
99      */

100     public String JavaDoc getAuthorization(HttpServletRequest JavaDoc req,HttpServletResponse JavaDoc res) throws AuthorizationException, NotLoggedInException {
101         return getAuthorization(req, res, "www", "Basic");
102     }
103
104     /**
105      * Authenticates a user, If the user cannot be authenticated a login-popup will appear
106      * @deprecation-used should call Security, not HttpAuth
107      * @param req The HttpServletRequest.
108      * @param res The HttpServletResponse.
109      * @param server server-account. (for exameple 'film' or 'www')
110      * @param level loginlevel. (for example 'Basic' or 'MD5')
111      * @exception AuthorizationException if the authorization fails.
112      * @exception NotLoggedInException if the user hasn't logged in yet.
113      */

114     public String JavaDoc getAuthorization(HttpServletRequest JavaDoc req,HttpServletResponse JavaDoc res,String JavaDoc server, String JavaDoc level) throws AuthorizationException, NotLoggedInException {
115         return HttpAuth.getAuthorization(req, res, server, level);
116     }
117
118     /**
119      * This method retrieves the users' MMBase cookie name & value as 'name/value'.
120      * When the cookie can't be found, a new cookie will be added.
121      * The cookies domain will be implicit or explicit depending on the MMBASEROOT.properties value.
122      * @dependency org.mmbase.module.builder.Properties should not depend on this builder ?
123      * @param req The HttpServletRequest.
124      * @param res The HttpServletResponse.
125      * @return A String with the users' MMBase cookie as 'name/value' or null when MMBase core module
126      * can't be found, or when the MMBase cookie is located but can't be retrieved from the cookies list.
127      */

128     public String JavaDoc getCookie(HttpServletRequest JavaDoc req, HttpServletResponse JavaDoc res) {
129
130         final String JavaDoc MMBASE_COOKIENAME = "MMBase_Ident";
131         //String FUTUREDATE = "Sunday, 09-Dec-2020 23:59:59 GMT"; // weird date?
132
final String JavaDoc PATH = "/";
133         String JavaDoc domain = null;
134         Cookie JavaDoc[] cookies = req.getCookies(); // Returns 1 or more cookie NAME=VALUE pairs seperated with a ';'.
135

136         if (cookies!= null) {
137             for (int i = 0; i < cookies.length; i++) {
138                 Cookie JavaDoc cookie = cookies[i];
139                 if (cookie.getName().equals(MMBASE_COOKIENAME)) {
140                     return MMBASE_COOKIENAME + '/' + cookie.getValue();
141                 }
142             }
143         }
144
145         log.debug("No mmbase cookie found");
146         // Added address in output to see if multiple cookies are being requested from same computer.
147
// This would imply improper use of our service :)
148
//
149
// added output to see why certain browsers keep asking for new cookie (giving a cookie
150
// with no reference in them with 'MMBASE_COOKIENAME'
151
// ------------------------------------------------------------------------------------------
152
MMBase mmbase = MMBase.getMMBase();
153         if (mmbase == null) {
154             log.warn("No mmbase found");
155             return null;
156         }
157         String JavaDoc cookieValue = "" + System.currentTimeMillis();
158         domain = mmbase.getInitParameter("COOKIEDOMAIN");
159         log.debug("Setting MMBase cookie on domain " + domain);
160         Cookie JavaDoc cookie = new Cookie JavaDoc(MMBASE_COOKIENAME, cookieValue);
161         cookie.setPath(PATH);
162         if (domain != null) {
163             cookie.setDomain(domain);
164         }
165         cookie.setMaxAge((int) (20 * 365.25 * 24 * 60 * 60));
166         res.addCookie(cookie);
167         if (res.isCommitted()) {
168             log.error("Could not add cookie " + cookie + " because response is already committed");
169         }
170         return MMBASE_COOKIENAME + '/' + cookieValue;
171
172     }
173
174     /**
175      * Get the parameter specified.
176      * @param req The HttpServletRequest.
177      */

178     public String JavaDoc getParam(HttpServletRequest JavaDoc req,int num) {
179         String JavaDoc str;
180
181         // needs a new caching way
182
Vector params=buildparams(req);
183         try {
184             str=(String JavaDoc)params.elementAt(num);
185         } catch(IndexOutOfBoundsException JavaDoc e) {
186             str=null;
187         }
188         return str;
189     }
190
191     /**
192      * Extracts the request line parameters.
193      * SCAN-format
194      * @param req The HttpServletRequest.
195      * @return a <code>Vector</code> with the request line parameters
196      */

197     private Vector buildparams(HttpServletRequest JavaDoc req) {
198         Vector params=new Vector();
199         if (req.getQueryString()!=null) {
200             StringTokenizer tok=new StringTokenizer(req.getQueryString(),"+\n\r");
201             // rico
202
while(tok.hasMoreTokens()) {
203                 params.addElement(tok.nextToken());
204             }
205         }
206         return params;
207     }
208
209     /**
210      * Get the Vector containing all parameters
211      * @param req The HttpServletRequest.
212      */

213     public Vector getParamVector(HttpServletRequest JavaDoc req) {
214         Vector params=buildparams(req);
215         return params;
216     }
217
218     /**
219      * @javadoc
220      * @vpro should be made configurable, possibly per servlet.
221      * The best way would likely be a system where a set of names can be configured
222      * (in other words, a hashtable with clientaddress/proxyname value pairs)
223      */

224     private static String JavaDoc VPROProxyName = "vpro6d.vpro.nl"; // name of proxyserver
225
/**
226      * @javadoc
227      * @vpro should be made configurable, possibly per servlet
228      */

229     private static String JavaDoc VPROProxyAddress = "145.58.172.6"; // address of proxyserver
230
/**
231      * @javadoc
232      * @vpro should be made configurable, possibly per servlet
233      */

234     private static String JavaDoc proxyName = "zen.vpro.nl"; // name of proxyserver
235

236     /**
237      * Extract hostname from request, get address and determine the proxies between it.
238      * Needed to determine if user comes from an internal or external host, i.e.
239      * when using two streaming servers, one for external users and one for internal users.
240      * @javadoc
241      * <br />
242      * @vpro uses VPROProxyName, VPROProxyAddress. Should be made more generic.
243      * @param req The HTTP request, which contains hostname as ipaddress
244      * @return a string containing the proxy chain. in the format
245      * "clientproxy.clientside.com->dialin07.clientside.com"
246      */

247     public String JavaDoc getAddress(HttpServletRequest JavaDoc req) {
248         String JavaDoc result = null;
249         boolean fromProxy = false;
250         String JavaDoc addr = req.getRemoteHost();
251
252         if( addr != null && !addr.equals("") ) {
253             // from proxy ?
254
// ------------
255
if( addr.indexOf( VPROProxyName ) != -1 || addr.indexOf( VPROProxyAddress ) != -1 ) {
256                 // get real address
257
// ----------------
258
fromProxy = true;
259                 addr = req.getHeader("X-Forwarded-For");
260                 if(addr != null && !addr.equals("")) {
261                     result = addr;
262                 }
263             } else {
264                 result = addr;
265             }
266         }
267         result = getHostNames( addr );
268         if( fromProxy ) {
269             result = proxyName+"->" + result;
270         }
271         return result;
272     }
273
274     /**
275      * Determine the host names of a String containing a comma-separated list of
276      * ip addresses and/or host names.
277      * Used to retrieve a list of proxies.
278      * @param host an comma-seperated String containing ip-addressed and/or host names
279      * @return a string containing the proxy chain. in the format
280      * "clientproxy.clientside.com->dialin07.clientside.com"
281      */

282     private String JavaDoc getHostNames( String JavaDoc host ) {
283         String JavaDoc result = null;
284         String JavaDoc hn = null;
285
286         // comes client from his own proxy?
287
// --------------------------------
288
if( host.indexOf(",") != -1 ) {
289             int pos;
290             // filter and display the clientproxies
291
// ------------------------------------
292
while( (pos = host.indexOf(",")) != -1) {
293                 hn = host.substring( 0, pos );
294                 host = host.substring( pos + 2 );
295                 if( result == null ) {
296                     result = getHostName( hn );
297                 } else {
298                     result += "->" + getHostName( hn );
299                 }
300             }
301             // which results in "proxy.clientside.com->dailin07.clientside.com"
302
// ----------------------------------------------------------------
303
} else {
304             result = getHostName( host );
305         }
306         return result;
307     }
308
309     /**
310      * Determine the host name of a passed ip address or host name.
311      * If the passed parameter is an IP-address, the hostname for
312      * that address is retrieved if possible.
313      * @param hostname an ip-address or host name
314      * @return the resulting hostname
315      */

316     private String JavaDoc getHostName( String JavaDoc hostname ) {
317         // if hostname == ipaddress, try to get a hostname for it
318
// ------------------------------------------------------
319

320         String JavaDoc hn = null;
321         if( hostname != null && !hostname.equals("")) {
322             try {
323                 hn = InetAddress.getByName( hostname ).getHostName();
324             } catch( UnknownHostException JavaDoc e ) {
325                 hn = hostname;
326             }
327         } else {
328             hn = hostname;
329         }
330         return hn;
331     }
332
333 }
334
Popular Tags