2 * Copyright (C) 2007-2012 Mathieu Baudier
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package org
.argeo
.slc
.web
.ajaxplorer
.file
;
19 import java
.io
.InputStream
;
20 import java
.io
.OutputStream
;
22 import javax
.servlet
.http
.HttpServletRequest
;
23 import javax
.servlet
.http
.HttpServletResponse
;
25 import org
.apache
.commons
.io
.FileUtils
;
26 import org
.apache
.commons
.io
.IOUtils
;
27 import org
.argeo
.slc
.web
.ajaxplorer
.AjxpAnswer
;
28 import org
.argeo
.slc
.web
.ajaxplorer
.AjxpDriverException
;
30 public abstract class AbstractFileDownloadAction
extends FileAction
{
31 public AjxpAnswer
execute(FileDriver driver
, HttpServletRequest request
) {
32 String fileStr
= request
.getParameter(getFileParameter());
33 if (fileStr
== null) {
34 throw new AjxpDriverException(
35 "A file to download needs to be provided.");
37 File file
= new File(driver
.getBasePath() + fileStr
);
38 return new AxpBasicDownloadAnswer(file
);
41 /** Return 'file' by default. */
42 protected String
getFileParameter() {
46 /** To be overridden. Do nothing by default. */
47 protected void setHeaders(HttpServletResponse response
, File file
) {
51 protected class AxpBasicDownloadAnswer
implements AjxpAnswer
{
52 private final File file
;
54 public AxpBasicDownloadAnswer(File file
) {
58 public void updateResponse(HttpServletResponse response
) {
59 InputStream in
= null;
60 OutputStream out
= null;
62 setHeaders(response
, file
);
64 if (log
.isDebugEnabled())
65 log
.debug("Download file " + file
);
66 in
= FileUtils
.openInputStream(file
);
67 out
= response
.getOutputStream();
72 } catch (Exception e
) {
74 throw new AjxpDriverException("Cannot download file " + file
, e
);
76 IOUtils
.closeQuietly(in
);
77 IOUtils
.closeQuietly(out
);
82 protected void copyFile(InputStream in
, OutputStream out
)
84 IOUtils
.copy(in
, out
);