KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > lutris > appserver > server > StandardAppUtil


1
2 /*
3  * Enhydra Java Application Server Project
4  *
5  * The contents of this file are subject to the Enhydra Public License
6  * Version 1.1 (the "License"); you may not use this file except in
7  * compliance with the License. You may obtain a copy of the License on
8  * the Enhydra web site ( http://www.enhydra.org/ ).
9  *
10  * Software distributed under the License is distributed on an "AS IS"
11  * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
12  * the License for the specific terms governing rights and limitations
13  * under the License.
14  *
15  * The Initial Developer of the Enhydra Application Server is Lutris
16  * Technologies, Inc. The Enhydra Application Server and portions created
17  * by Lutris Technologies, Inc. are Copyright Lutris Technologies, Inc.
18  * All Rights Reserved.
19  *
20  * Contributor(s):
21  *
22  * $Id: StandardAppUtil.java,v 1.4 2005/04/21 10:02:33 lola Exp $
23  */

24
25 package com.lutris.appserver.server;
26
27 import java.net.InetAddress JavaDoc;
28 import java.net.MalformedURLException JavaDoc;
29 import java.net.URL JavaDoc;
30 import java.net.UnknownHostException JavaDoc;
31 import java.util.StringTokenizer JavaDoc;
32
33 import javax.servlet.ServletRequest JavaDoc;
34 import javax.servlet.http.Cookie JavaDoc;
35 import javax.servlet.http.HttpServletRequest JavaDoc;
36
37 import com.lutris.appserver.server.httpPresentation.HttpPresentationComms;
38 import com.lutris.appserver.server.httpPresentation.HttpPresentationException;
39 import com.lutris.appserver.server.session.Session;
40 import com.lutris.appserver.server.session.SessionException;
41 import com.lutris.appserver.server.session.SessionManager;
42
43
44 /**
45  * Static methods used by <CODE>StandardApplication</CODE>. These mostly
46  * are used to manage sessions.
47  *
48  * @version $Revision: 1.4 $
49  * @author Mark Diekhans
50  * @author Richard Kunze <kunze@opus5.de>
51  */

52 public class StandardAppUtil {
53
54     /*
55      * Constant used for encoding the session in a url rewrite.
56      */

57     public static final String JavaDoc ENHYDRA_SESSION_ID_URL = "jsessionid";
58     public static final String JavaDoc ENHYDRA_SESSION_ID_COOKIE = "JSESSIONID";
59
60     /**
61      * Prevent instantiation.
62      */

63     private StandardAppUtil() {
64     }
65
66     /**
67      * Get internet peer address.
68      *
69      * @param comms The presentations manager comms object with
70      * all request/response information in it.
71      * @return The peer address.
72      * @exception ApplicationException If address can't be obtained.
73      */

74     //FIXME: no longer needed, but might make a nice general util function.
75
public static InetAddress JavaDoc[] getPeerAddress(HttpPresentationComms comms)
76             throws ApplicationException {
77
78         InetAddress JavaDoc[] peer = new InetAddress JavaDoc[1];
79         String JavaDoc remoteHost;
80         try {
81             remoteHost = comms.request.getRemoteHost();
82         } catch (HttpPresentationException except) {
83             throw new ApplicationException(except);
84         }
85         if (remoteHost == null) {
86             throw new ApplicationException("Can't find remote host for request.");
87         }
88         if (remoteHost != null) {
89             try {
90                 peer[0] = InetAddress.getByName(remoteHost);
91             } catch (UnknownHostException JavaDoc except) {
92                 throw new ApplicationException("Can't find remote address for \"" + remoteHost + "\"", except);
93             }
94         }
95         return peer;
96     }
97
98     /**
99      * Search for a session cookie with the specified application name.
100      *
101      * @param applicationName Application name that is saved in the cookie.
102      * @param cookies Array of cookies for the current request.
103      * @return The session key decoded from the cookie, or null if
104      * the session was not found.
105      * @deprecated
106      */

107     private static String JavaDoc findSessionKey(String JavaDoc applicationName,
108                                          Cookie JavaDoc[] cookies) {
109     return findSessionKey(cookies);
110     }
111
112     /**
113      * Search for a session cookie with the name jsessionid.
114      *
115      * @param applicationName Application name that is saved in the cookie.
116      * @param cookies Array of cookies for the current request.
117      * @return The session key decoded from the cookie, or null if
118      * the session was not found.
119      * @deprecated
120      */

121     private static String JavaDoc findSessionKey(Cookie JavaDoc[] cookies) {
122         if (cookies == null) {
123             return null;
124         }
125     for (int i=0; i<cookies.length; i++) {
126         if (cookies[i].getName().equalsIgnoreCase(ENHYDRA_SESSION_ID_COOKIE)) {
127                 return cookies[i].getValue();
128         }
129     }
130         return null;
131     }
132
133     /**
134      * Encode a URL with a session identifier.
135      *
136      * @param url The url to encode.
137      * @param id The session identifier to encode with the url.
138      */

139     public static String JavaDoc encodeUrl(String JavaDoc url, String JavaDoc id) {
140         String JavaDoc pre = url;
141         String JavaDoc post = "";
142         int pos;
143         // Need to put the parameters before a local anchor
144
if ((pos = url.indexOf('?')) != -1 ||
145             (pos = url.indexOf('#')) != -1) {
146             pre = url.substring(0, pos);
147             post = url.substring(pos);
148         }
149     return pre + ';' + ENHYDRA_SESSION_ID_URL + '=' + id + post;
150     }
151
152     /**
153      * Determine if a URL references a presentation object. Used for
154      * URL rewriting to test if a session ID should be appended to a
155      * given URL. Takes the cheap way out at the moment in that it
156      * simply returns true iff (if and only if, for the
157      * non-mathematicians :-) the URL contains the character sequence
158      * <code>.po</code>.
159      * <br>
160      * TODO: Implement a better check
161      * A safety check has been added by Petr Stehlik on 2002/11/05
162      * First, it strips a query and fragment parts of the URL, since
163      * both the query and the fragment may contain ".po" that
164      * confuses the original algorithm.
165      * <br>
166      * Example: <code>http://www.server.org/path/file.html?query=page.po</code>
167      * <br>
168      * The function now correctly returns false for the URL above.
169      *
170      * @param url The url to check
171      * @return True if the URL points to a PO, false otherwise
172      */

173     public static boolean pointsToPO(String JavaDoc url) {
174     // int idx = url.indexOf(".po");
175
// first, strip any query and fragment
176
int idx = url.indexOf('?'); // is there a query?
177
if (idx == -1) {
178             idx = url.indexOf('#'); // or is there a fragment?
179
}
180         if (idx > 0) {
181             url = url.substring(0, idx); // strip them!
182
}
183
184         // now check for the ".po" (should be at the end of the URL)
185
idx = url.indexOf(".po");
186         if (idx == -1) {
187             return false;
188         }
189         if (idx == url.length()-3) {
190             return true;
191         }
192    /* switch (url.charAt(idx+3)) {
193             case '?':
194             case '#':
195                 return true;
196             case '/':
197                 // A bit more difficult: Need to decide if it's in the
198                 // the server or URI part of the URL.
199                 try {
200                     URL u = new URL(url);
201                     int i = u.getFile().indexOf(".po");
202                     return (i != -1);
203                 } catch (MalformedURLException e) {
204                     // url doesn't contain a schema and/or server
205                     // part, so it must be relative. OK, found a PO.
206                     return true;
207                 }
208             default:
209                 return false;
210     */

211         // if it's not at the end of the URL then decide if it's in the URI
212
if (url.charAt(idx+3) == '/') {
213             // A bit more difficult: Need to decide if it's in the
214
// the server or URI part of the URL.
215
try {
216                             URL JavaDoc u = new URL JavaDoc(url);
217                             int i = u.getFile().indexOf(".po");
218                             return (i != -1);
219                         } catch (MalformedURLException JavaDoc e) {
220                             // url doesn't contain a schema and/or server
221
// part, so it must be relative. OK, found a PO.
222
return true;
223                         }
224               }
225           return false;
226     }
227
228
229     /**
230      * Determine if a session exists for this request. Does not
231      * validate that a session is logged in.
232      *
233      * @param comms The presentations manager comms object with
234      * all request/response information in it.
235      * @return The session object or null if a session cookie or
236      * matching session is not found.
237      * @exception ApplicationException If address can't be obtained.
238      */

239     public static Session getRequestSession(HttpPresentationComms comms)
240             throws ApplicationException {
241         Session s = null;
242         String JavaDoc sessionKey = null;
243         Cookie JavaDoc[] cookies;
244   SessionManager sessionManager = (SessionManager)comms.application.getSessionManager();
245
246         try {
247       if (!sessionManager.getEncodeUrlState().equalsIgnoreCase(SessionManager.ENCODE_URL_ALWAYS)) {
248         cookies = comms.request.getCookies();
249         sessionKey = findSessionKey(ENHYDRA_SESSION_ID_COOKIE,
250                         cookies);
251         if (sessionKey != null) {
252             // These are set so that application programmers
253
// can determine the state of session cookies if not
254
// using automatic url encoding
255
comms.request.setRequestedSessionIdFromCookie(true);
256             comms.request.setRequestedSessionIdFromUrl(false);
257             comms.response.setSessionIdCookieRequired(true);
258             comms.response.setSessionIdEncodeUrlRequired(false);
259         }
260             }
261
262       if (!sessionManager.getEncodeUrlState().equalsIgnoreCase(SessionManager.ENCODE_URL_NEVER)
263           && sessionKey == null) {
264
265                 //
266
// This needs to be redone.
267
//
268
// if (comms.request.getHttpServletRequest() instanceof EnhydraRequest ) {
269
// EnhydraRequest er = (EnhydraRequest) comms.request.getHttpServletRequest();
270
// }
271

272         // Check if sessionKey is encoded as a parameter in the path
273
// info (the form is http://localhost/foo.po;jsessionid=XYZ
274
HttpServletRequest JavaDoc servletRequest = comms.request.getHttpServletRequest();
275         sessionKey = servletRequest.getRequestedSessionId();
276         if (sessionKey != null) {
277           if (servletRequest.isRequestedSessionIdFromURL()) {
278             comms.request.setRequestedSessionIdFromUrl(true);
279             comms.request.setRequestedSessionIdFromCookie(false);
280             comms.response.setSessionIdEncodeUrlRequired(true);
281             comms.response.setSessionIdCookieRequired(false);
282           }
283         }
284         else {
285                 String JavaDoc pathInfo = comms.request.getPathInfo();
286         StringTokenizer JavaDoc tokens =
287             new StringTokenizer JavaDoc(pathInfo, "/\\;=", false);
288         while (tokens.hasMoreTokens()) {
289             String JavaDoc param = tokens.nextToken();
290             if (param.equalsIgnoreCase(ENHYDRA_SESSION_ID_URL)) {
291             sessionKey = tokens.nextToken();
292             break;
293             }
294         }
295
296             if (sessionKey != null) {
297                     // These are set so that application programmers
298
// can determine the state of session cookies if not
299
// using automatic url encoding
300
comms.request.setRequestedSessionIdFromUrl(true);
301                 comms.request.setRequestedSessionIdFromCookie(false);
302             comms.response.setSessionIdEncodeUrlRequired(true);
303             comms.response.setSessionIdCookieRequired(false);
304             }
305             }
306    }
307         } catch (HttpPresentationException except2) {
308             throw new ApplicationException(except2);
309         }
310     if (sessionKey == null) {
311         return null;
312     }
313
314     if (!sessionManager.getEncodeUrlState().equalsIgnoreCase(SessionManager.ENCODE_URL_NEVER)) {
315         comms.response.setSessionKey(sessionKey);
316         comms.response.setSessionManager(comms.application.getSessionManager());
317     }
318         try {
319       s = comms.application.getSessionManager().getSession(Thread.currentThread(),
320                // sessionKey);
321
sessionKey, comms);
322         } catch (SessionException e) {
323             throw new ApplicationException(e);
324         }
325         return s;
326     }
327
328     /**
329      * This is a rarely used utility function. Give a raw ServletRequest,
330      * the session cookie used to look up the session object that would be
331      * used with the request if it were passed into the Enhydra framework.
332      * Returns null if no cookie or session is found; a new session will
333      * not be created.
334      * Currently this is only used to support the debugger.
335      *
336      * @param request
337      * The raw request.
338      * @param application
339      * The application that will be servicing the request.
340      * @return
341      * The session object that would be used if the request were
342      * passed into the Enhydra framework, or null if not found (no new
343      * session will be created).
344      */

345     public static Session getRequestSession(ServletRequest JavaDoc request,
346                                             Application application)
347             throws ApplicationException {
348         if (application == null) {
349             return null;
350         }
351         Cookie JavaDoc[] cookies;
352         Session s;
353         HttpServletRequest JavaDoc req;
354         try {
355             req = (HttpServletRequest JavaDoc)request;
356         } catch (ClassCastException JavaDoc e) {
357             return null;
358         }
359         cookies = req.getCookies();
360         String JavaDoc sessionKey = findSessionKey(cookies);
361         if (sessionKey == null) {
362             return null;
363         }
364         SessionManager sm = application.getSessionManager();
365         if (sm == null) {
366             return null;
367         }
368         try {
369             s = sm.getSession(Thread.currentThread(), sessionKey);
370         } catch (SessionException e) {
371             throw new ApplicationException(e);
372         }
373         return s;
374     }
375
376
377     /**
378      * Associate a new <CODE>StandardSession<CODE> to a client cookie.
379      *
380      * @param comms The presentations manager comms object with
381      * all request/response information in it.
382      * @exception ApplicationException If address can't be obtained.
383      */

384     public static void bindSessionToClient(HttpPresentationComms comms)
385             throws ApplicationException {
386
387     Session session = (Session)comms.session;
388    SessionManager sessionManager = (SessionManager)session.getSessionManager();
389     if (!sessionManager.getEncodeUrlState().equalsIgnoreCase(SessionManager.ENCODE_URL_ALWAYS)) {
390         try {
391         Cookie JavaDoc cookie = new Cookie JavaDoc(ENHYDRA_SESSION_ID_COOKIE, session.getSessionKey());
392         // cookie.setPath(comms.request.getApplicationPath());
393
String JavaDoc cookiePath = comms.request.getApplicationPath();
394         
395         if(cookiePath!=null)
396         {
397          cookiePath.trim();
398          if(cookiePath.endsWith("/") && cookiePath.length()>1)
399           {
400             cookiePath = cookiePath.substring(0,cookiePath.length()-1);
401           }
402         }
403         cookie.setPath(cookiePath);
404       
405         String JavaDoc serverName = comms.request.getServerName();
406   // Do not set the domain (PJ).
407
/*
408         int first = serverName.indexOf('.');
409         int last = serverName.lastIndexOf('.');
410         if ((first > -1) && (last > -1) && (first != last)) {
411             cookie.setDomain(serverName.substring(first));
412         }
413 */

414         comms.response.addCookie(cookie);
415         } catch (HttpPresentationException except) {
416         throw new ApplicationException(except);
417         }
418     }
419     if (!sessionManager.getEncodeUrlState().equalsIgnoreCase(SessionManager.ENCODE_URL_NEVER)) {
420         comms.response.setSessionKey(comms.session.getSessionKey());
421         comms.response.setSessionManager(comms.application.getSessionManager());
422     }
423     }
424 }
425
Popular Tags