This repository was archived by the owner on Mar 18, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathFileStoreServlet.java
More file actions
480 lines (438 loc) · 15.1 KB
/
Copy pathFileStoreServlet.java
File metadata and controls
480 lines (438 loc) · 15.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
/*
* net/balusc/webapp/FileServlet.java
*
* Copyright (C) 2009 BalusC
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
package edu.ucsd.library.dams.api;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Map;
import java.util.Properties;
import java.util.zip.GZIPOutputStream;
import java.text.SimpleDateFormat;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import edu.ucsd.library.dams.file.FileStore;
import edu.ucsd.library.dams.file.FileStoreException;
import edu.ucsd.library.dams.file.FileStoreUtil;
/**
* A file servlet supporting client-side caching and GZIP of text content.
* This servlet can also be used for images, client-side caching would become
* more efficient. This servlet can also be used for text files, GZIP would
* decrease network bandwidth.
*
* @author BalusC
* @link http://balusc.blogspot.com/2009/02/fileservlet-supporting-resume-and.html
*
* Retrieved 2011-02-04, modified with filename/path, authorization logic, etc.
* Ported to exclusive FileStore usage 2012-05-23.
* @author escowles@ucsd.edu
* @author lsitu@ucsd.edu
*/
public class FileStoreServlet extends HttpServlet
{
/* begin ucsd changes */
private static Logger log = Logger.getLogger( FileStoreServlet.class );
/* end ucsd changes */
// Constants ---------------------------------------------------------
private static final int DEFAULT_BUFFER_SIZE = 10240; // ..bytes = 10KB.
private static final long DEFAULT_EXPIRE_TIME = 604800000L; // ..ms = 1 week
// Properties --------------------------------------------------------
private String fsDefault;
private Properties props;
private SimpleDateFormat df;
// Actions -----------------------------------------------------------
/**
* Initialize the servlet.
* @see HttpServlet#init().
*/
public void init() throws ServletException
{
/* begin ucsd changes */
try
{
InitialContext ctx = new InitialContext();
String damsHome = null;
try
{
damsHome = (String)ctx.lookup("java:comp/env/dams/home");
}
catch ( Exception ex )
{
damsHome = "dams";
}
props = DAMSAPIServlet.loadConfig();
fsDefault = props.getProperty("fs.default");
df = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
// RFC 822, Wed, 23 May 2012 11:54:18 GMT
}
catch ( Exception ex )
{
log.warn("Unable to lookup default filestore", ex );
throw new ServletException("Unable to lookup default filestore");
}
/* end ucsd changes */
}
/**
* Process HEAD request. This returns the same headers as GET request, but
* without content.
* @see HttpServlet#doHead(HttpServletRequest, HttpServletResponse).
*/
protected void doHead( HttpServletRequest request,
HttpServletResponse response ) throws ServletException, IOException
{
// Process request without content.
processRequest(request, response, false);
}
/**
* Process GET request.
* @see HttpServlet#doGet(HttpServletRequest, HttpServletResponse).
*/
protected void doGet( HttpServletRequest request,
HttpServletResponse response ) throws ServletException, IOException
{
// Process request with content.
processRequest(request, response, true);
}
/**
* Process the actual request.
* @param request The request to be processed.
* @param response The response to be created.
* @param content Whether the request body should be written (GET) or not
* (HEAD).
* @throws IOException If something fails at I/O level.
*/
private void processRequest ( HttpServletRequest request,
HttpServletResponse response, boolean content) throws IOException
{
// Validate the requested file -------------------------------------
// Get requested file by path info.
/* start ucsd changes */
// get object and file ids from path
String objid = null;
String cmpid = null;
String fileid = null;
try
{
// /bb1234567x/1.tif
// /bb1234567x/1/2.tif
String[] path = request.getPathInfo().split("/");
if ( path.length == 3 )
{
objid = path[1];
fileid = path[2];
}
else if ( path.length == 4 )
{
objid = path[1];
cmpid = path[2];
fileid = path[3];
}
}
catch (Exception e)
{
String errorMessage = "Error parsing request pathInfo: " + request.getPathInfo();
log.error( errorMessage, e );
response.setContentType("text/plain");
response.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, errorMessage );
return;
}
// make sure required parameters are populated
if ( objid == null || objid.trim().length() == 0
|| fileid == null || fileid.trim().length() == 0 )
{
response.setContentType("text/plain");
response.sendError( HttpServletResponse.SC_BAD_REQUEST,
"Subject and file must be specified in the request URI" );
return;
}
String fullFilename = objid + (StringUtils.isNotBlank(cmpid) ? "-" + cmpid : "") + "-" + fileid;
// first load the FileStore (no point if this doesn't work)
FileStore fs = null;
long fsTime = 0;
try
{
long start = System.currentTimeMillis();
fs = FileStoreUtil.getFileStore( props, fsDefault );
fsTime = System.currentTimeMillis() - start;
}
catch ( Exception ex )
{
response.setContentType("text/plain");
response.sendError(
response.SC_INTERNAL_SERVER_ERROR,
"Error initializing FileStore"
);
ex.printStackTrace();
return;
}
// check authorization attribute
String restricted = null;
String authorized = (String) request.getAttribute(
"edu.ucsd.library.dams.api.DAMSAPIServlet.authorized"
);
if(authorized == null || !authorized.equals("true"))
{
log.warn("Illegal Access from IP " + request.getRemoteAddr()
+ " for file " + fullFilename);
response.setContentType("text/plain");
response.sendError( HttpServletResponse.SC_FORBIDDEN,
"Access without authorization.");
return;
}
else
{
log.info( "DAMS Access authorized for IP " + request.getRemoteAddr()
+ " for file " + fullFilename);
restricted = (String)request.getAttribute("pas.restricted");
//Disable browser caching for restricted objects.
if(restricted != null && restricted.equals("1"))
{
String browser = request.getHeader("User-Agent");
if(browser != null && browser.indexOf("MSIE") != -1)
{
response.addHeader("Cache-Control",
"post-check=0, pre-check=0");
}
else
{
response.setHeader("Cache-Control",
"no-store, no-cache, must-revalidate");
}
response.setHeader("Pragma", "no-cache");
response.setHeader("Expires", "0");
}
}
/* end ucsd changes */
// load file metadata
Map<String,String> meta = null;
long metaTime = 0;
try
{
long start = System.currentTimeMillis();
meta = fs.meta( objid, cmpid, fileid );
metaTime = System.currentTimeMillis() - start;
}
catch ( Exception ex )
{
log.error("File " + fullFilename + " doesn't exist.", ex);
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
// Prepare some variables. The ETag is an unique identifier of the file
String length = meta.get("Content-Length");
String lastModStr = meta.get("Last-Modified");
long lastModified = 0L;
try
{
lastModified = df.parse( lastModStr ).getTime();
}
catch ( Exception ex )
{
// error parsing lastmod date... set to now
lastModified = System.currentTimeMillis();
}
String eTag = meta.get("ETag");
if ( eTag == null )
{
eTag = fullFilename + "_" + length + "_" + lastModified;
}
// Validate request headers for caching -----------------------------
// If-None-Match header should contain "*" or ETag. If so, return 304.
String ifNoneMatch = request.getHeader("If-None-Match");
if (ifNoneMatch != null && matches(ifNoneMatch, eTag)) {
response.setHeader("ETag", eTag); // Required in 304.
response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
return;
}
// If-Modified-Since header should be greater than LastModified. If so,
// then return 304.
// This header is ignored if any If-None-Match header is specified.
long ifModifiedSince = request.getDateHeader("If-Modified-Since");
if (ifNoneMatch == null && ifModifiedSince != -1
&& ifModifiedSince + 1000 > lastModified) {
response.setHeader("ETag", eTag); // Required in 304.
response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
return;
}
// Validate request headers for resume ------------------------------
// If-Match header should contain "*" or ETag. If not, then return 412.
String ifMatch = request.getHeader("If-Match");
if (ifMatch != null && !matches(ifMatch, eTag)) {
response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
return;
}
// If-Unmodified-Since header should be greater than LastModified.
// If not, then return 412.
long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since");
if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified)
{
response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
return;
}
// Prepare and initialize response ----------------------------------
// Get content type by file name and set default GZIP support and
// content disposition.
String contentType = getServletContext().getMimeType(fullFilename);
boolean acceptsGzip = false;
String disposition = "inline";
// If content type is unknown, then set the default value. For all
// content types, see: http://www.w3schools.com/media/media_mimeref.asp
// To add new content types, add new mime-mapping entry in web.xml.
if (contentType == null) {
contentType = "application/octet-stream";
}
//If UCSD download
boolean download = request.getParameter("download") != null;
if( download ){
disposition = "attachment";
contentType = "application/x-download";
}
// Else if content type is text, then determine whether GZIP content
// encoding is supported by the browser and expand content type with
// the one and right character encoding.
else if (contentType.startsWith("text")) {
//String acceptEncoding = request.getHeader("Accept-Encoding");
//acceptsGzip = acceptEncoding != null && accepts(acceptEncoding, "gzip");
contentType += ";charset=UTF-8";
}
// Else, expect for images, determine content disposition. If content
// type is supported by the browser, then set to inline, else
// attachment which will pop a 'save as' dialogue.
else if (!contentType.startsWith("image")) {
String accept = request.getHeader("Accept");
disposition = accept != null && accepts(accept, contentType) ? "inline" : "attachment";
}
String sFileName = request.getParameter("name");
if(sFileName == null || (sFileName=sFileName.trim()).length()==0)
sFileName = fullFilename;
// Initialize response.
response.reset();
response.setBufferSize(DEFAULT_BUFFER_SIZE);
response.setHeader("Content-Disposition",
disposition + ";filename=\"" + sFileName + "\"");
response.setHeader("ETag", eTag);
response.setDateHeader("Last-Modified", lastModified);
/* begin ucsd changes */
if( restricted == null || !restricted.equals("1") )
{
response.setDateHeader("Expires",
System.currentTimeMillis() + DEFAULT_EXPIRE_TIME);
}
/* end ucsd changes */
// Send requested file to client ------------------------------------
// Prepare streams.
InputStream input = null;
OutputStream output = null;
long fileTime = 0;
if (content)
{
try
{
long start = System.currentTimeMillis();
// Open streams.
input = fs.getInputStream(objid,cmpid,fileid);
output = response.getOutputStream();
response.setContentType(contentType);
if (acceptsGzip)
{
// The browser accepts GZIP, so GZIP the content.
response.setHeader("Content-Encoding", "gzip");
output = new GZIPOutputStream(output, DEFAULT_BUFFER_SIZE);
}
else
{
// Content length is not directly predictable in case of
// GZIP. So only add it if there is no means of GZIP, else
// browser will hang.
response.setHeader("Content-Length", length);
}
// Copy full range.
/* begin ucsd changes */
FileStoreUtil.copy(input, output);
fileTime = System.currentTimeMillis() - start;
/* begin ucsd changes */
}
catch ( Exception ex )
{
log.error("Error reading " + fullFilename, ex );
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
finally
{
/* begin ucsd changes */
log.info("Time in miliseconds to retrival file " + fullFilename + "(" + length + " bytes)" + ": Total " + (fsTime + metaTime + fileTime) + "[FileStore initiation: " + fsTime + "; Metadata query: " + metaTime + "; File download: " + fileTime + "]");
/* begin ucsd changes */
// Gently close streams.
close(output);
close(input);
}
}
}
// Helpers (can be refactored to public utility class) --------------------
/**
* Returns true if the given accept header accepts the given value.
* @param acceptHeader The accept header.
* @param toAccept The value to be accepted.
* @return True if the given accept header accepts the given value.
*/
private static boolean accepts(String acceptHeader, String toAccept) {
String[] acceptValues = acceptHeader.split("\\s*(,|;)\\s*");
Arrays.sort(acceptValues);
return Arrays.binarySearch(acceptValues, toAccept) > -1
|| Arrays.binarySearch(acceptValues, toAccept.replaceAll("/.*$", "/*")) > -1
|| Arrays.binarySearch(acceptValues, "*/*") > -1;
}
/**
* Returns true if the given match header matches the given value.
* @param matchHeader The match header.
* @param toMatch The value to be matched.
* @return True if the given match header matches the given value.
*/
private static boolean matches(String matchHeader, String toMatch) {
String[] matchValues = matchHeader.split("\\s*,\\s*");
Arrays.sort(matchValues);
return Arrays.binarySearch(matchValues, toMatch) > -1
|| Arrays.binarySearch(matchValues, "*") > -1;
}
/**
* Close the given resource.
* @param resource The resource to be closed.
*/
private static void close(Closeable resource) {
if (resource != null) {
try {
resource.close();
} catch (IOException ignore) {
// Ignore IOException. If you want to handle this anyway, it
// might be useful to know that this will generally only be
// thrown when the client aborted the request.
}
}
}
}