KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > jnlp > sample > servlet > JnlpDownloadServlet


1 /*
2  * @(#)JnlpDownloadServlet.java 1.10 07/03/15
3  *
4  * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions are met:
8  *
9  * -Redistribution of source code must retain the above copyright notice, this
10  * list of conditions and the following disclaimer.
11  *
12  * -Redistribution in binary form must reproduce the above copyright notice,
13  * this list of conditions and the following disclaimer in the documentation
14  * and/or other materials provided with the distribution.
15  *
16  * Neither the name of Sun Microsystems, Inc. or the names of contributors may
17  * be used to endorse or promote products derived from this software without
18  * specific prior written permission.
19  *
20  * This software is provided "AS IS," without a warranty of any kind. ALL
21  * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
22  * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
23  * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
24  * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
25  * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
26  * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
27  * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
28  * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
29  * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
30  * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
31  *
32  * You acknowledge that this software is not designed, licensed or intended
33  * for use in the design, construction, operation or maintenance of any
34  * nuclear facility.
35  */

36
37 package jnlp.sample.servlet;
38
39 import java.io.*;
40 import java.util.*;
41 import java.net.*;
42 import javax.servlet.*;
43 import javax.servlet.http.*;
44
45 /**
46  * This Servlet class is an implementation of JNLP Specification's
47  * Download Protocols.
48  *
49  * All requests to this servlet is in the form of HTTP GET commands.
50  * The parameters that are needed are:
51  * <ul>
52  * <li><code>arch</code>,
53  * <li><code>os</code>,
54  * <li><code>locale</code>,
55  * <li><code>version-id</code> or <code>platform-version-id</code>,
56  * <li><code>current-version-id</code>,
57  * <li>code>known-platforms</code>
58  * </ul>
59  * <p>
60  *
61  * @version 1.8 01/23/03
62  */

63 public class JnlpDownloadServlet extends HttpServlet {
64     
65     // Localization
66
private static ResourceBundle _resourceBundle = null;
67     
68     // Servlet configuration
69
private static final String JavaDoc PARAM_JNLP_EXTENSION = "jnlp-extension";
70     private static final String JavaDoc PARAM_JAR_EXTENSION = "jar-extension";
71     
72     // Servlet configuration
73
private Logger _log = null;
74     
75     private JnlpFileHandler _jnlpFileHandler = null;
76     private JarDiffHandler _jarDiffHandler = null;
77     private ResourceCatalog _resourceCatalog = null;
78     
79     /** Initialize servlet */
80     public void init(ServletConfig config) throws ServletException {
81         super.init(config);
82     
83     
84     // Setup logging
85
_log = new Logger(config, getResourceBundle());
86     _log.addDebug("Initializing");
87     
88     // Get extension from Servlet configuration, or use default
89
JnlpResource.setDefaultExtensions(
90         config.getInitParameter(PARAM_JNLP_EXTENSION),
91         config.getInitParameter(PARAM_JAR_EXTENSION));
92     
93     _jnlpFileHandler = new JnlpFileHandler(config.getServletContext(), _log);
94     _jarDiffHandler = new JarDiffHandler(config.getServletContext(), _log);
95     _resourceCatalog = new ResourceCatalog(config.getServletContext(), _log);
96     }
97     
98     public static synchronized ResourceBundle getResourceBundle() {
99     if (_resourceBundle == null) {
100         _resourceBundle = ResourceBundle.getBundle("jnlp/sample/servlet/resources/strings");
101     }
102     return _resourceBundle;
103     }
104     
105     
106     public void doHead(HttpServletRequest request, HttpServletResponse response)
107         throws ServletException, IOException {
108         handleRequest(request, response, true);
109     }
110     
111     /** We handle get requests too - eventhough the spec. only requeres POST requests */
112     public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
113         handleRequest(request, response, false);
114     }
115     
116     private void handleRequest(HttpServletRequest request,
117             HttpServletResponse response, boolean isHead) throws IOException {
118     String JavaDoc requestStr = request.getRequestURI();
119     if (request.getQueryString() != null) requestStr += "?" + request.getQueryString().trim();
120     
121     // Parse HTTP request
122
DownloadRequest dreq = new DownloadRequest(getServletContext(), request);
123     if (_log.isInformationalLevel()) {
124         _log.addInformational("servlet.log.info.request", requestStr);
125         _log.addInformational("servlet.log.info.useragent", request.getHeader("User-Agent"));
126     }
127     if (_log.isDebugLevel()) {
128         _log.addDebug(dreq.toString());
129     }
130        
131         long ifModifiedSince = request.getDateHeader("If-Modified-Since");
132
133     // Check if it is a valid request
134
try {
135         // Check if the request is valid
136
validateRequest(dreq);
137         
138         // Decide what resource to return
139
JnlpResource jnlpres = locateResource(dreq);
140         _log.addDebug("JnlpResource: " + jnlpres);
141         
142         
143         if (_log.isInformationalLevel()) {
144         _log.addInformational("servlet.log.info.goodrequest", jnlpres.getPath());
145         }
146     
147             DownloadResponse dres = null;
148             
149             if (isHead) {
150                 
151                 int cl =
152                       jnlpres.getResource().openConnection().getContentLength();
153         
154                 // head request response
155
dres = DownloadResponse.getHeadRequestResponse(
156                         jnlpres.getMimeType(), jnlpres.getVersionId(),
157                         jnlpres.getLastModified(), cl);
158                 
159             } else if (ifModifiedSince != -1 &&
160                     (ifModifiedSince / 1000) >=
161                     (jnlpres.getLastModified() / 1000)) {
162                 // We divide the value returned by getLastModified here by 1000
163
// because if protocol is HTTP, last 3 digits will always be
164
// zero. However, if protocol is JNDI, that's not the case.
165
// so we divide the value by 1000 to remove the last 3 digits
166
// before comparison
167

168                 // return 304 not modified if possible
169
_log.addDebug("return 304 Not modified");
170                 dres = DownloadResponse.getNotModifiedResponse();
171             
172             } else {
173                 
174                 // Return selected resource
175
dres = constructResponse(jnlpres, dreq);
176             }
177             
178         dres.sendRespond(response);
179         
180     } catch(ErrorResponseException ere) {
181         if (_log.isInformationalLevel()) {
182         _log.addInformational("servlet.log.info.badrequest", requestStr);
183         }
184         if (_log.isDebugLevel()) {
185         _log.addDebug("Response: "+ ere.toString());
186         }
187         // Return response from exception
188
ere.getDownloadResponse().sendRespond(response);
189     } catch(Throwable JavaDoc e) {
190         _log.addFatal("servlet.log.fatal.internalerror", e);
191         response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
192     }
193     }
194     
195     /** Make sure that it is a valid request. This is also the place to implement the
196      * reverse IP lookup
197      */

198     private void validateRequest(DownloadRequest dreq) throws ErrorResponseException {
199     String JavaDoc path = dreq.getPath();
200     if (path.endsWith(ResourceCatalog.VERSION_XML_FILENAME) ||
201         path.indexOf("__") != -1 ) {
202         throw new ErrorResponseException(DownloadResponse.getNoContentResponse());
203         }
204     }
205     
206     /** Interprets the download request and convert it into a resource that is
207      * part of the Web Archive.
208      */

209     private JnlpResource locateResource(DownloadRequest dreq) throws IOException, ErrorResponseException {
210     if (dreq.getVersion() == null) {
211         return handleBasicDownload(dreq);
212     } else {
213         return handleVersionRequest(dreq);
214     }
215     }
216     
217     private JnlpResource handleBasicDownload(DownloadRequest dreq) throws ErrorResponseException, IOException {
218     _log.addDebug("Basic Protocol lookup");
219     // Do not return directory names for basic protocol
220
if (dreq.getPath() == null || dreq.getPath().endsWith("/")) {
221         throw new ErrorResponseException(DownloadResponse.getNoContentResponse());
222     }
223     // Lookup resource
224
JnlpResource jnlpres = new JnlpResource(getServletContext(), dreq.getPath());
225     if (!jnlpres.exists()) {
226         throw new ErrorResponseException(DownloadResponse.getNoContentResponse());
227     }
228     return jnlpres;
229     }
230     
231     private JnlpResource handleVersionRequest(DownloadRequest dreq) throws IOException, ErrorResponseException {
232     _log.addDebug("Version-based/Extension based lookup");
233     return _resourceCatalog.lookupResource(dreq);
234     }
235     
236     /** Given a DownloadPath and a DownloadRequest, it constructs the data stream to return
237      * to the requester
238      */

239     private DownloadResponse constructResponse(JnlpResource jnlpres, DownloadRequest dreq) throws IOException {
240     String JavaDoc path = jnlpres.getPath();
241     if (jnlpres.isJnlpFile()) {
242         // It is a JNLP file. It need to be macro-expanded, so it is handled differently
243
boolean supportQuery = JarDiffHandler.isJavawsVersion(dreq, "1.5+");
244         _log.addDebug("SupportQuery in Href: " + supportQuery);
245
246         // only support query string in href for 1.5 and above
247
if (supportQuery) {
248         return _jnlpFileHandler.getJnlpFileEx(jnlpres, dreq);
249         } else {
250         return _jnlpFileHandler.getJnlpFile(jnlpres, dreq);
251         }
252     }
253     
254     // Check if a JARDiff can be returned
255
if (dreq.getCurrentVersionId() != null && jnlpres.isJarFile()) {
256         DownloadResponse response = _jarDiffHandler.getJarDiffEntry(_resourceCatalog, dreq, jnlpres);
257         if (response != null) {
258         _log.addInformational("servlet.log.info.jardiff.response");
259         return response;
260         }
261     }
262
263     // check and see if we can use pack resource
264
JnlpResource jr = new JnlpResource(getServletContext(),
265                     jnlpres.getName(),
266                     jnlpres.getVersionId(),
267                     jnlpres.getOSList(),
268                     jnlpres.getArchList(),
269                     jnlpres.getLocaleList(),
270                     jnlpres.getPath(),
271                     jnlpres.getReturnVersionId(),
272                     dreq.getEncoding());
273     
274         _log.addDebug("Real resource returned: " + jr);
275     
276     // Return WAR file resource
277
return DownloadResponse.getFileDownloadResponse(jr.getResource(),
278                             jr.getMimeType(),
279                             jr.getLastModified(),
280                             jr.getReturnVersionId());
281     }
282 }
283
284
285
Popular Tags