KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sslexplorer > replacementproxy > ReplacementProxyMethodHandler


1 /*
2  * SSL-Explorer
3  *
4  * Copyright (C) 2003-2006 3SP LTD. All Rights Reserved
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2 of
9  * the License, or (at your option) any later version.
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public
16  * License along with this program; if not, write to the Free Software
17  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  */

19             
20 package com.sslexplorer.replacementproxy;
21
22 import java.io.File JavaDoc;
23 import java.io.IOException JavaDoc;
24 import java.io.OutputStream JavaDoc;
25 import java.util.HashSet JavaDoc;
26 import java.util.Iterator JavaDoc;
27
28 import org.apache.commons.logging.Log;
29 import org.apache.commons.logging.LogFactory;
30
31 import com.sslexplorer.boot.ContextHolder;
32 import com.sslexplorer.boot.RequestHandlerException;
33 import com.sslexplorer.boot.RequestHandlerRequest;
34 import com.sslexplorer.boot.RequestHandlerResponse;
35 import com.sslexplorer.core.CookieMap;
36 import com.sslexplorer.core.CoreUtil;
37 import com.sslexplorer.policyframework.LaunchSession;
38 import com.sslexplorer.policyframework.LaunchSessionFactory;
39 import com.sslexplorer.properties.Property;
40 import com.sslexplorer.properties.impl.systemconfig.SystemConfigKey;
41 import com.sslexplorer.security.Constants;
42 import com.sslexplorer.security.SessionInfo;
43 import com.sslexplorer.security.User;
44 import com.sslexplorer.webforwards.AbstractAuthenticatingWebForwardHandler;
45 import com.sslexplorer.webforwards.WebForwardPlugin;
46
47 /**
48  * Request handler that deals with both <i>Replacement Proxy</i> web forwards.
49  *
50  * @author Lee David Painter <a HREF="mailto: lee@3sp.com">&lt;lee@3sp.com&gt;</a>
51  * @author Brett Smith <a HREF="mailto: brett@3sp.com">&lt;brett@3sp.com&gt;</a>
52  */

53 public class ReplacementProxyMethodHandler extends AbstractAuthenticatingWebForwardHandler {
54
55     final static String JavaDoc sessionCookie = System.getProperty("sslexplorer.cookie", "JSESSIONID");
56
57     static HashSet JavaDoc<String JavaDoc> ignoredHeaders = new HashSet JavaDoc<String JavaDoc>();
58
59     static {
60         ignoredHeaders.add("Location".toUpperCase());
61         ignoredHeaders.add("Server".toUpperCase());
62         ignoredHeaders.add("Date".toUpperCase());
63     }
64
65     static Log log = LogFactory.getLog(ReplacementProxyMethodHandler.class);
66
67     public boolean handle(String JavaDoc pathInContext, String JavaDoc pathParams, RequestHandlerRequest request, RequestHandlerResponse response)
68                     throws RequestHandlerException, IOException JavaDoc {
69         if (log.isDebugEnabled())
70             log.debug("Checking for Replacement proxy request: " + pathInContext);
71         
72         LaunchSession launchSession = null;
73         
74         String JavaDoc launchId;
75
76         try {
77             String JavaDoc requestPath = request.getPath();
78             if (requestPath.startsWith("/replacementProxyEngine")) {
79
80
81                 /* The launch session and URL may be provided in one of two ways.
82                  *
83                  * 1. As a request to /replacementProxyEngine with the launch session
84                  * and target URL provided as sslx_launchId and sslx_url respectively
85                  *
86                  * 2. In the new format /replacementProxyEngine/[launchId]/[encodedURL]
87                  */

88                 
89                 if(requestPath.startsWith("/replacementProxyEngine/")) {
90                     int idx = requestPath.indexOf('/', 1);
91                     int idx2 = requestPath.indexOf('/', idx + 1);
92                     launchId = requestPath.substring(idx + 1, idx2);
93                 }
94                 else {
95                     launchId = (String JavaDoc) request.getParameters().get(LaunchSession.LONG_LAUNCH_ID);
96                 }
97                 
98                 if (launchId != null) {
99                     LaunchSession foundLaunchSession = LaunchSessionFactory.getInstance().getLaunchSession(launchId);
100                     if (foundLaunchSession == null) {
101                         response.sendError(404, "Invalid launch session. Your SSL-Explorer session has probobably timed out.");
102                         return true;
103                     }
104                     if (foundLaunchSession.isTracked() && foundLaunchSession.getResource()
105                                     .getResourceType()
106                                     .equals(WebForwardPlugin.WEBFORWARD_RESOURCE_TYPE)) {
107                         launchSession = foundLaunchSession;
108                         if (log.isDebugEnabled()) {
109                             log.debug("Found a web forward launch session provided by " + LaunchSession.LONG_LAUNCH_ID
110                                 + " parameter in request.");
111                         }
112                         SessionInfo session = locateSession(request, response);
113                         if (session == null) {
114                             throw new Exception JavaDoc("Session could not be located.");
115                         }
116                         launchSession.checkAccessRights(null, session);
117                         return handleReplacementProxy(request, response, launchSession);
118                     }
119                 }
120             }
121         } catch (Exception JavaDoc e) {
122             log.error("Failed to process web forward.", e);
123             if (launchSession != null) {
124                 launchSession.getSession().getHttpSession().setAttribute(Constants.EXCEPTION, e);
125                 response.sendRedirect("/showPopupException.do");
126             } else {
127                 throw new RequestHandlerException("Failed to process web forward.", 500);
128             }
129             return true;
130         }
131         return false;
132     }
133
134     private boolean handleReplacementProxy(RequestHandlerRequest request, RequestHandlerResponse response,
135                                             LaunchSession launchSession) throws Exception JavaDoc {
136
137         int maxAge = Property.getPropertyInt(new SystemConfigKey("webForwards.cache.maxUserAge")) * 1000 * 60;
138         User user = launchSession.getSession().getUser();
139         ContentCache cache = getCache(launchSession.getSession(), user);
140         CookieMap cookieMap = getCookieMap(launchSession);
141
142         final RequestProcessor requestProcessor = new RequestProcessor(cache, maxAge, request, launchSession);
143
144         try {
145
146             // Process the request
147
requestProcessor.processRequest();
148
149             // Get the page from cache if the request processor determined it
150
// could be
151
if (requestProcessor.isGetFromCache()) {
152                 if (log.isDebugEnabled())
153                     log.debug("Found page in cache");
154                 CacheingOutputStream cos = (CacheingOutputStream) cache.retrieve(requestProcessor.getRequestParameters()
155                                 .getProxiedURL());
156                 respondFromCache(cos, request, response);
157                 return true;
158             }
159
160             // Send the request to the proxied host
161
ProxiedRequestDispatcher requestDispatcher = new ProxiedRequestDispatcher(requestProcessor, launchSession, cookieMap);
162
163             if (!requestDispatcher.sendProxiedRequest()) {
164                 response.sendError(requestDispatcher.getResponseCode(), requestDispatcher.getResponseMessage());
165                 return true;
166             }
167
168             // Process the proxied hosts response =
169
ProxiedResponseProcessor proxiedResponseProcessor = new ProxiedResponseProcessor(requestProcessor,
170                             requestDispatcher,
171                             maxAge,
172                             cache,
173                             cookieMap);
174             proxiedResponseProcessor.processResponse();
175
176             // Send the response
177
ProxiedResponseDispatcher responseDispatcher = new ProxiedResponseDispatcher(this, requestProcessor,
178                             proxiedResponseProcessor,
179                             response,
180                             launchSession,
181                             cache);
182
183             responseDispatcher.sendResponse();
184         } catch (Throwable JavaDoc t) {
185             log.error("Serious error proxying request.", t);
186             if (t instanceof Exception JavaDoc) {
187                 throw (Exception JavaDoc) t;
188             }
189             throw new Exception JavaDoc("Internal error.", t);
190         }
191         return true;
192     }
193
194     /**
195      * Get the cookie for the session.
196      *
197      * @param session session
198      * @return cookie map
199      */

200     public CookieMap getCookieMap(LaunchSession launchSession) {
201         if (log.isDebugEnabled())
202             log.debug("Getting cookie map for " + launchSession.getId() + " (" + launchSession.hashCode() + ")");
203         CookieMap cookieMap = (CookieMap) launchSession.getAttribute(Constants.ATTR_COOKIE_MAP);
204         if (cookieMap == null) {
205             if (log.isDebugEnabled())
206                 log.debug("Creating new cookie map");
207             cookieMap = new CookieMap();
208             launchSession.setAttribute(Constants.ATTR_COOKIE_MAP, cookieMap);
209         }
210         return cookieMap;
211
212     }
213
214     private ContentCache getCache(SessionInfo session, User user) throws Exception JavaDoc {
215
216         ContentCache cache = (ContentCache) session.getHttpSession().getAttribute(Constants.ATTR_CACHE);
217         if (cache == null) {
218             int maxObjs = Property.getPropertyInt(new SystemConfigKey("webForwards.cache.maxUserObjects"));
219             if (maxObjs != 0) {
220                 String JavaDoc dir = CoreUtil.replaceAllTokens(Property.getProperty(new SystemConfigKey("webForwards.cache.directory")),
221                     "%TMP%",
222                     ContextHolder.getContext().getTempDirectory().getAbsolutePath());
223                 File JavaDoc cacheDir = new File JavaDoc(dir);
224                 if (!cacheDir.exists()) {
225                     if (!cacheDir.mkdirs()) {
226                         throw new Exception JavaDoc("Could not create cache directory " + cacheDir.getAbsolutePath() + ".");
227                     }
228                 }
229                 cache = new ContentCache(user,
230                                 cacheDir,
231                                 Property.getPropertyInt(new SystemConfigKey("webForwards.cache.maxUserSize")),
232                                 maxObjs);
233                 session.getHttpSession().setAttribute(Constants.ATTR_CACHE, cache);
234             }
235         }
236         return cache;
237     }
238
239     /**
240      * @param cos
241      * @param request
242      * @param response
243      * @throws IOException
244      */

245     private void respondFromCache(CacheingOutputStream cos, RequestHandlerRequest request, RequestHandlerResponse response)
246                     throws IOException JavaDoc {
247         for (Iterator JavaDoc i = cos.getHeaders().iterator(); i.hasNext();) {
248             Header h = (Header) i.next();
249             response.setField(h.getName(), h.getVal());
250         }
251         response.setField("Content-Type", cos.getContentType());
252         OutputStream JavaDoc out = response.getOutputStream();
253         byte[] buf = cos.getBytes();
254         response.setContentLength(buf.length);
255         out.write(buf);
256         out.flush();
257
258     }
259
260 }
261
Popular Tags