KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > help > internal > webapp > servlet > EclipseConnector


1 /*******************************************************************************
2  * Copyright (c) 2000, 2007 IBM Corporation and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Eclipse Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/epl-v10.html
7  *
8  * Contributors:
9  * IBM Corporation - initial API and implementation
10  *******************************************************************************/

11 package org.eclipse.help.internal.webapp.servlet;
12
13 import java.io.BufferedInputStream JavaDoc;
14 import java.io.ByteArrayInputStream JavaDoc;
15 import java.io.IOException JavaDoc;
16 import java.io.InputStream JavaDoc;
17 import java.io.OutputStream JavaDoc;
18 import java.io.PrintWriter JavaDoc;
19 import java.io.StringWriter JavaDoc;
20 import java.io.Writer JavaDoc;
21 import java.lang.reflect.UndeclaredThrowableException JavaDoc;
22 import java.net.URL JavaDoc;
23 import java.net.URLConnection JavaDoc;
24 import java.util.Enumeration JavaDoc;
25 import java.util.Locale JavaDoc;
26
27 import javax.servlet.ServletContext JavaDoc;
28 import javax.servlet.http.HttpServletRequest JavaDoc;
29 import javax.servlet.http.HttpServletResponse JavaDoc;
30
31 import org.eclipse.help.internal.base.BaseHelpSystem;
32 import org.eclipse.help.internal.protocols.HelpURLConnection;
33 import org.eclipse.help.internal.protocols.HelpURLStreamHandler;
34 import org.eclipse.help.internal.webapp.HelpWebappPlugin;
35 import org.eclipse.help.internal.webapp.data.ServletResources;
36 import org.eclipse.help.internal.webapp.data.UrlUtil;
37
38 /**
39  * Performs transfer of data from eclipse to a jsp/servlet
40  */

41 public class EclipseConnector {
42     private static final String JavaDoc errorPageBegin = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\n" //$NON-NLS-1$
43
+ "<html><head>\n" //$NON-NLS-1$
44
+ "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n" //$NON-NLS-1$
45
+ "</head>\n" //$NON-NLS-1$
46
+ "<body><p>\n"; //$NON-NLS-1$
47
private static final String JavaDoc errorPageEnd = "</p></body></html>"; //$NON-NLS-1$
48
private static final IFilter filters[] = new IFilter[]{
49             new HighlightFilter(), new FramesetFilter(), new InjectionFilter(), new DynamicXHTMLFilter(), new BreadcrumbsFilter() };
50     private ServletContext JavaDoc context;
51
52     public EclipseConnector(ServletContext JavaDoc context) {
53         this.context= context;
54     }
55
56     public void transfer(HttpServletRequest JavaDoc req, HttpServletResponse JavaDoc resp)
57             throws IOException JavaDoc {
58         try {
59             String JavaDoc url = getURL(req);
60             if (url == null)
61                 return;
62             // Redirect if the request includes PLUGINS_ROOT and is not a content request
63
int index = url.lastIndexOf(HelpURLConnection.PLUGINS_ROOT);
64             if (index!= -1 && url.indexOf("content/" + HelpURLConnection.PLUGINS_ROOT) == -1) { //$NON-NLS-1$
65
StringBuffer JavaDoc redirectURL = new StringBuffer JavaDoc();
66                 
67                 redirectURL.append(req.getContextPath());
68                 redirectURL.append(req.getServletPath());
69                 redirectURL.append("/"); //$NON-NLS-1$
70
redirectURL.append(url.substring(index+HelpURLConnection.PLUGINS_ROOT.length()));
71                 
72                 resp.sendRedirect(redirectURL.toString());
73                 return;
74             }
75             if (url.toLowerCase(Locale.ENGLISH).startsWith("file:") //$NON-NLS-1$
76
|| url.toLowerCase(Locale.ENGLISH).startsWith("jar:") //$NON-NLS-1$
77
|| url.toLowerCase(Locale.ENGLISH).startsWith("platform:")) { //$NON-NLS-1$
78
int i = url.indexOf('?');
79                 if (i != -1)
80                     url = url.substring(0, i);
81                 // ensure the file is only accessed from a local installation
82
if (BaseHelpSystem.getMode() == BaseHelpSystem.MODE_INFOCENTER
83                         || !UrlUtil.isLocalRequest(req)) {
84                     return;
85                 }
86             } else {
87                 // enable activities matching url
88
// HelpBasePlugin.getActivitySupport().enableActivities(url);
89

90                 url = "help:" + url; //$NON-NLS-1$
91
}
92
93             URLConnection JavaDoc con = openConnection(url, req, resp);
94             String JavaDoc contentType = con.getContentType();
95             if ("text/plain".equals(contentType)) { //$NON-NLS-1$
96
// URLConnection.getContentType() defaults to "text/plain",
97
// use the context to get a more reliable result.
98
String JavaDoc pathInfo = req.getPathInfo();
99                 String JavaDoc mimeType = context.getMimeType(pathInfo);
100                 if (mimeType != null) {
101                     contentType = mimeType;
102                 }
103             }
104             resp.setContentType(contentType);
105
106             long maxAge = 0;
107             try {
108                 // getExpiration() throws NullPointerException when URL is
109
// jar:file:...
110
long expiration = con.getExpiration();
111                 maxAge = (expiration - System.currentTimeMillis()) / 1000;
112                 if (maxAge < 0)
113                     maxAge = 0;
114             } catch (Exception JavaDoc e) {
115             }
116             resp.setHeader("Cache-Control", "max-age=" + maxAge); //$NON-NLS-1$ //$NON-NLS-2$
117

118             InputStream JavaDoc is;
119             try {
120                 is = con.getInputStream();
121             } catch (IOException JavaDoc ioe) {
122                 if (url.toLowerCase(Locale.ENGLISH).endsWith("htm") //$NON-NLS-1$
123
|| url.toLowerCase(Locale.ENGLISH).endsWith("html")) { //$NON-NLS-1$
124
String JavaDoc error = errorPageBegin
125                             + ServletResources.getString("noTopic", req) //$NON-NLS-1$
126
+ errorPageEnd;
127                     is = new ByteArrayInputStream JavaDoc(error.getBytes("UTF8")); //$NON-NLS-1$
128
} else {
129                     return;
130                 }
131             }
132             catch (Exception JavaDoc e) {
133                 // if it's a wrapped exception, unwrap it
134
Throwable JavaDoc t = e;
135                 if (t instanceof UndeclaredThrowableException JavaDoc && t.getCause() != null) {
136                     t = t.getCause();
137                 }
138
139                 StringBuffer JavaDoc message = new StringBuffer JavaDoc();
140                 message.append(errorPageBegin);
141                 message.append("<p>"); //$NON-NLS-1$
142
message.append(ServletResources.getString(
143                         "contentProducerException", //$NON-NLS-1$
144
req));
145                 message.append("</p>"); //$NON-NLS-1$
146
message.append("<pre>"); //$NON-NLS-1$
147
Writer JavaDoc writer = new StringWriter JavaDoc();
148                 t.printStackTrace(new PrintWriter JavaDoc(writer));
149                 message.append(writer.toString());
150                 message.append("</pre>"); //$NON-NLS-1$
151
message.append(errorPageEnd);
152                 
153                 is = new ByteArrayInputStream JavaDoc(message.toString().getBytes("UTF8")); //$NON-NLS-1$
154
}
155
156             OutputStream JavaDoc out = resp.getOutputStream();
157             for (int i = 0; i < filters.length; i++) {
158                 out = filters[i].filter(req, out);
159             }
160
161             transferContent(is, out);
162             out.close();
163             is.close();
164
165         } catch (Exception JavaDoc e) {
166             String JavaDoc msg = "Error processing help request " + getURL(req); //$NON-NLS-1$
167
HelpWebappPlugin.logError(msg, e);
168         }
169     }
170
171     /**
172      * Write the body to the response
173      */

174     private void transferContent(InputStream JavaDoc inputStream, OutputStream JavaDoc out)
175             throws IOException JavaDoc {
176         try {
177             // Prepare the input stream for reading
178
BufferedInputStream JavaDoc dataStream = new BufferedInputStream JavaDoc(
179                     inputStream);
180
181             // Create a fixed sized buffer for reading.
182
// We could create one with the size of availabe data...
183
byte[] buffer = new byte[4096];
184             int len = 0;
185             while (true) {
186                 len = dataStream.read(buffer); // Read file into the byte array
187
if (len == -1)
188                     break;
189                 out.write(buffer, 0, len);
190             }
191         } catch (Exception JavaDoc e) {
192         }
193     }
194
195     /**
196      * Gets content from the named url (this could be and eclipse defined url)
197      */

198     private URLConnection JavaDoc openConnection(String JavaDoc url,
199             HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response)
200             throws Exception JavaDoc {
201         
202         URLConnection JavaDoc con = null;
203         if (BaseHelpSystem.getMode() == BaseHelpSystem.MODE_INFOCENTER) {
204             // it is an infocentre, add client locale to url
205
String JavaDoc locale = UrlUtil.getLocale(request, response);
206             if (url.indexOf('?') >= 0) {
207                 url = url + "&lang=" + locale; //$NON-NLS-1$
208
} else {
209                 url = url + "?lang=" + locale; //$NON-NLS-1$
210
}
211         }
212         URL JavaDoc helpURL;
213         if (url.startsWith("help:")) { //$NON-NLS-1$
214
helpURL = new URL JavaDoc("help", //$NON-NLS-1$
215
null, -1, url.substring("help:".length()), //$NON-NLS-1$
216
HelpURLStreamHandler.getDefault());
217         } else {
218             if (url.startsWith("jar:")) { //$NON-NLS-1$
219
// fix for bug 83929
220
int excl = url.indexOf("!/"); //$NON-NLS-1$
221
String JavaDoc jar = url.substring(0, excl);
222                 String JavaDoc path = url.length() > excl + 2 ? url.substring(excl + 2)
223                         : ""; //$NON-NLS-1$
224
url = jar.replaceAll("!", "%21") + "!/" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
225
+ path.replaceAll("!", "%21"); //$NON-NLS-1$ //$NON-NLS-2$
226
}
227             helpURL = new URL JavaDoc(url);
228         }
229         String JavaDoc protocol = helpURL.getProtocol();
230         if (!("help".equals(protocol) //$NON-NLS-1$
231
|| "file".equals(protocol) //$NON-NLS-1$
232
|| "platform".equals(protocol) //$NON-NLS-1$
233
|| "jar".equals(protocol))) { //$NON-NLS-1$
234
throw new IOException JavaDoc();
235         }
236
237         con = helpURL.openConnection();
238
239         con.setAllowUserInteraction(false);
240         con.setDoInput(true);
241         con.connect();
242         return con;
243     }
244
245     /**
246      * Extracts the url from a request
247      */

248     private String JavaDoc getURL(HttpServletRequest JavaDoc req) {
249         String JavaDoc query = ""; //$NON-NLS-1$
250
boolean firstParam = true;
251         for (Enumeration JavaDoc params = req.getParameterNames(); params
252                 .hasMoreElements();) {
253             String JavaDoc param = (String JavaDoc) params.nextElement();
254             String JavaDoc[] values = req.getParameterValues(param);
255             if (values == null)
256                 continue;
257             for (int i = 0; i < values.length; i++) {
258                 if (firstParam) {
259                     query += "?" + param + "=" + values[i]; //$NON-NLS-1$ //$NON-NLS-2$
260
firstParam = false;
261                 } else
262                     query += "&" + param + "=" + values[i]; //$NON-NLS-1$ //$NON-NLS-2$
263
}
264         }
265
266         // the request contains the eclipse url help: or search:
267
String JavaDoc url = req.getPathInfo() + query;
268         if (url.startsWith("/")) //$NON-NLS-1$
269
url = url.substring(1);
270         return url;
271     }
272 }
273
Popular Tags