KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sslexplorer > applications > actions > GetHTMLApplicationAction


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.applications.actions;
21
22 import java.io.BufferedReader JavaDoc;
23 import java.io.File JavaDoc;
24 import java.io.FileInputStream JavaDoc;
25 import java.io.InputStream JavaDoc;
26 import java.io.InputStreamReader JavaDoc;
27 import java.io.OutputStream JavaDoc;
28 import java.io.OutputStreamWriter JavaDoc;
29 import java.io.PrintWriter JavaDoc;
30 import java.net.URL JavaDoc;
31 import java.util.Iterator JavaDoc;
32 import java.util.Map JavaDoc;
33 import java.util.StringTokenizer JavaDoc;
34 import java.util.regex.Matcher JavaDoc;
35 import java.util.regex.Pattern JavaDoc;
36
37 import javax.servlet.http.HttpServletRequest JavaDoc;
38 import javax.servlet.http.HttpServletResponse JavaDoc;
39
40 import org.apache.commons.logging.Log;
41 import org.apache.commons.logging.LogFactory;
42 import org.apache.struts.action.ActionForm;
43 import org.apache.struts.action.ActionForward;
44 import org.apache.struts.action.ActionMapping;
45
46 import com.sslexplorer.applications.ApplicationShortcut;
47 import com.sslexplorer.applications.ApplicationShortcutEventConstants;
48 import com.sslexplorer.applications.types.HtmlType;
49 import com.sslexplorer.boot.HttpConstants;
50 import com.sslexplorer.boot.ReplacementEngine;
51 import com.sslexplorer.boot.Replacer;
52 import com.sslexplorer.boot.Util;
53 import com.sslexplorer.core.CoreAttributeConstants;
54 import com.sslexplorer.core.CoreEvent;
55 import com.sslexplorer.core.CoreServlet;
56 import com.sslexplorer.core.actions.AuthenticatedAction;
57 import com.sslexplorer.core.stringreplacement.VariableReplacement;
58 import com.sslexplorer.extensions.ExtensionDescriptor;
59 import com.sslexplorer.extensions.store.ExtensionStore;
60 import com.sslexplorer.policyframework.LaunchSession;
61 import com.sslexplorer.policyframework.LaunchSessionFactory;
62 import com.sslexplorer.policyframework.Policy;
63 import com.sslexplorer.policyframework.PolicyDatabaseFactory;
64 import com.sslexplorer.policyframework.ResourceAccessEvent;
65 import com.sslexplorer.security.Constants;
66 import com.sslexplorer.security.SessionInfo;
67
68 /**
69  * Authenticated action that processes the HTML templates provided by
70  * {@link com.sslexplorer.extensions.ApplicationLauncher} extensions that have a
71  * type of {@link com.sslexplorer.applications.types.HtmlType}.
72  * <p>
73  * The HTML template source is loaded and content within it is replaced by the
74  * application shortcuts parameters (and other standard replacements) before
75  * being returned to the client.
76  * <p>
77  * This may be used to provide support for ActiveX or Java applet application
78  * extensions.
79  * <p>
80  * The
81  * {@link #onExecute(ActionMapping, ActionForm, HttpServletRequest, HttpServletResponse)}
82  * method requires a single <b>id</b> parameter that is the resource ID of the required
83  * application shortcut.
84  * <p>
85  * A second optional <b>sslexplorer</b> parameter may be provided that should
86  * contain the HTTPS URL of the SSL-Explorer server as the client sees it it.
87  * This information is made available as a further template replacement value.
88  *
89  * @author Brett Smith <a HREF="mailto: brett@3sp.com">&lt;brett@3sp.com&gt;</a>
90  */

91 public class GetHTMLApplicationAction extends AuthenticatedAction {
92
93     final static Log log = LogFactory.getLog(GetHTMLApplicationAction.class);
94     final static String JavaDoc VARIABLE_PATTERN = "\\$\\{[^}]*\\}";
95
96     /**
97      * Constructor
98      */

99     public GetHTMLApplicationAction() {
100         super();
101     }
102
103     /* (non-Javadoc)
104      * @see com.sslexplorer.core.actions.AuthenticatedAction#onExecute(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
105      */

106     public ActionForward onExecute(ActionMapping mapping, ActionForm form, HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response)
107                     throws Exception JavaDoc {
108         String JavaDoc launchSessionId = request.getParameter(LaunchSession.LAUNCH_ID);
109         LaunchSession launchSession = LaunchSessionFactory.getInstance().getLaunchSession(launchSessionId);
110         if (launchSession == null) {
111             throw new Exception JavaDoc("No launch session id " + launchSessionId);
112         }
113         final ApplicationShortcut shortcut = (ApplicationShortcut)launchSession.getResource();
114         launchSession.checkAccessRights(null, getSessionInfo(request));
115         ExtensionDescriptor app = ExtensionStore.getInstance().getExtensionDescriptor(shortcut.getApplication());
116         if (app == null) {
117             throw new Exception JavaDoc("No application named " + shortcut.getApplication() + ".");
118         }
119
120         if (!(app.getExtensionType() instanceof HtmlType)) {
121             throw new Exception JavaDoc(getClass().getName() + " only supports applications of type " + HtmlType.class + ".");
122         }
123
124         // Get the primary VPN client ticket
125

126         HtmlType type = (HtmlType) app.getExtensionType();
127         File JavaDoc file = new File JavaDoc(app.getApplicationBundle().getBaseDir(), type.getTemplate());
128         if (log.isDebugEnabled())
129             log.debug("Loading template " + file.getAbsolutePath());
130
131         InputStream JavaDoc in = null;
132         StringBuffer JavaDoc template = new StringBuffer JavaDoc((int) file.length());
133         try {
134             in = new FileInputStream JavaDoc(file);
135             String JavaDoc line = null;
136             BufferedReader JavaDoc reader = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(in));
137             while ((line = reader.readLine()) != null) {
138                 if (template.length() != 0) {
139                     template.append("\n");
140                 }
141                 template.append(line);
142             }
143         } finally {
144             Util.closeStream(in);
145         }
146
147         if (log.isDebugEnabled())
148             log.debug("Parsing parameters.");
149         for (Iterator JavaDoc i = shortcut.getParameters().entrySet().iterator(); i.hasNext();) {
150             Map.Entry JavaDoc entry = (Map.Entry JavaDoc) i.next();
151             String JavaDoc content = (String JavaDoc) entry.getValue();
152             
153             VariableReplacement r = new VariableReplacement();
154             r.setApplicationShortcut(app, null);
155             r.setServletRequest(request);
156             r.setLaunchSession(launchSession);
157             
158             entry.setValue(r.replace(content));
159         }
160
161         if (log.isDebugEnabled())
162             log.debug("Template loaded, doing standard replacements.");
163
164         VariableReplacement r = new VariableReplacement();
165         r.setApplicationShortcut(app, shortcut.getParameters());
166         r.setServletRequest(request);
167         r.setLaunchSession(launchSession);
168         String JavaDoc templateText = r.replace(template.toString());
169
170         ReplacementEngine engine = new ReplacementEngine();
171
172         String JavaDoc tunnels = request.getParameter("tunnels");
173         if (tunnels != null && !tunnels.equals("")) {
174             StringTokenizer JavaDoc t = new StringTokenizer JavaDoc(tunnels, ",");
175             while (t.hasMoreTokens()) {
176                 String JavaDoc name = null;
177                 String JavaDoc hostname = null;
178                 int port = -1;
179                 try {
180                     String JavaDoc tunnel = t.nextToken();
181                     StringTokenizer JavaDoc t2 = new StringTokenizer JavaDoc(tunnel, ":");
182                     name = t2.nextToken();
183                     hostname = t2.nextToken();
184                     port = Integer.parseInt(t2.nextToken());
185                 } catch (Exception JavaDoc e) {
186                     throw new Exception JavaDoc("Failed to parse tunnels parameter '" + tunnels + "'.", e);
187                 }
188                 final ExtensionDescriptor.TunnelDescriptor tunnelDescriptor = app.getTunnel(name);
189                 if (tunnelDescriptor == null) {
190                     throw new Exception JavaDoc("No tunnel named " + name);
191                 }
192                 final String JavaDoc fHostname = hostname;
193                 final int fPort = port;
194                 String JavaDoc pattern = "\\$\\{tunnel:" + name + "\\.[^\\}]*\\}";
195                 engine.addPattern(pattern, new Replacer() {
196                     public String JavaDoc getReplacement(Pattern JavaDoc pattern, Matcher JavaDoc matcher, String JavaDoc sequence) {
197                         String JavaDoc match = matcher.group();
198                         if (match.equals("${tunnel:" + tunnelDescriptor.getName() + ".hostname}")) {
199                             return fHostname;
200                         } else if (match.equals("${tunnel:" + tunnelDescriptor.getName() + ".port}")) {
201                             return String.valueOf(fPort);
202                         } else {
203                             return "";
204                         }
205                     }
206                 }, null);
207
208             }
209         }
210
211         // Get the location of SSL Explorer as the client sees it
212
String JavaDoc url = request.getParameter("sslexplorer");
213         if (url != null) {
214             String JavaDoc host = request.getHeader(HttpConstants.HDR_HOST);
215             if (host != null) {
216                 url = (request.isSecure() ? "https" : "http") + "://" + host;
217             } else {
218
219                 throw new Exception JavaDoc("No sslexplorer parameter supplied.");
220             }
221         }
222         final URL JavaDoc sslexplorerUrl = new URL JavaDoc(url);
223         engine.addPattern("\\$\\{sslexplorer:[^\\}]*\\}", new Replacer() {
224             public String JavaDoc getReplacement(Pattern JavaDoc pattern, Matcher JavaDoc matcher, String JavaDoc sequence) {
225                 String JavaDoc match = matcher.group();
226                 try {
227                     String JavaDoc param = match.substring(14, match.length() - 1);
228                     if (param.equals("host")) {
229                         return sslexplorerUrl.getHost();
230                     } else if (param.equals("port")) {
231                         return String.valueOf(sslexplorerUrl.getPort() == -1 ? (sslexplorerUrl.getProtocol().equals("https") ? 443
232                                         : 80) : sslexplorerUrl.getPort());
233                     } else if (param.equals("protocol")) {
234                         return sslexplorerUrl.getProtocol();
235                     } else {
236                         throw new Exception JavaDoc("Unknow variable.");
237                     }
238                 } catch (Throwable JavaDoc t) {
239                     log.error("Failed to replace " + match + ".", t);
240                 }
241                 return "";
242             }
243         }, null);
244
245         String JavaDoc processed = engine.replace(templateText);
246         if (log.isDebugEnabled())
247             log.debug("Returning " + processed);
248
249         Util.noCache(response);
250
251         response.setContentType("text/html");
252         response.setContentLength(processed.length());
253         request.setAttribute(Constants.REQ_ATTR_COMPRESS, Boolean.FALSE);
254
255         OutputStream JavaDoc out = response.getOutputStream();
256         PrintWriter JavaDoc pw = new PrintWriter JavaDoc(new OutputStreamWriter JavaDoc(out));
257         pw.print(processed);
258         pw.flush();
259
260         Policy pol = PolicyDatabaseFactory.getInstance().getGrantingPolicyForUser(launchSession.getSession().getUser(), shortcut);
261         CoreServlet.getServlet().fireCoreEvent(new ResourceAccessEvent(this, ApplicationShortcutEventConstants.APPLICATION_SHORTCUT_LAUNCHED, shortcut, pol, launchSession.getSession(), CoreEvent.STATE_SUCCESSFUL)
262         .addAttribute(CoreAttributeConstants.EVENT_ATTR_APPLICATION_NAME, app.getName())
263         .addAttribute(CoreAttributeConstants.EVENT_ATTR_APPLICATION_ID, shortcut.getApplication()));
264         //////////////////////////////////////////////
265

266         return null;
267     }
268
269     /* (non-Javadoc)
270      * @see com.sslexplorer.core.actions.CoreAction#getNavigationContext(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
271      */

272     public int getNavigationContext(ActionMapping mapping, ActionForm form, HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
273         return SessionInfo.MANAGEMENT_CONSOLE_CONTEXT | SessionInfo.USER_CONSOLE_CONTEXT;
274     }
275 }
276
Popular Tags