]> git.argeo.org Git - gpl/argeo-slc.git/blob - legacy/runtime/org.argeo.slc.server/src/main/java/org/argeo/slc/web/ajaxplorer/file/AbstractFileDownloadAction.java
Restructure SLC
[gpl/argeo-slc.git] / legacy / runtime / org.argeo.slc.server / src / main / java / org / argeo / slc / web / ajaxplorer / file / AbstractFileDownloadAction.java
1 /*
2 * Copyright (C) 2007-2012 Mathieu Baudier
3 *
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
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
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.
15 */
16 package org.argeo.slc.web.ajaxplorer.file;
17
18 import java.io.File;
19 import java.io.InputStream;
20 import java.io.OutputStream;
21
22 import javax.servlet.http.HttpServletRequest;
23 import javax.servlet.http.HttpServletResponse;
24
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;
29
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.");
36 }
37 File file = new File(driver.getBasePath() + fileStr);
38 return new AxpBasicDownloadAnswer(file);
39 }
40
41 /** Return 'file' by default. */
42 protected String getFileParameter() {
43 return "file";
44 }
45
46 /** To be overridden. Do nothing by default. */
47 protected void setHeaders(HttpServletResponse response, File file) {
48 // do nothing
49 }
50
51 protected class AxpBasicDownloadAnswer implements AjxpAnswer {
52 private final File file;
53
54 public AxpBasicDownloadAnswer(File file) {
55 this.file = file;
56 }
57
58 public void updateResponse(HttpServletResponse response) {
59 InputStream in = null;
60 OutputStream out = null;
61 try {
62 setHeaders(response, file);
63
64 if (log.isDebugEnabled())
65 log.debug("Download file " + file);
66 in = FileUtils.openInputStream(file);
67 out = response.getOutputStream();
68
69 copyFile(in, out);
70 out.flush();
71
72 } catch (Exception e) {
73 e.printStackTrace();
74 throw new AjxpDriverException("Cannot download file " + file, e);
75 } finally {
76 IOUtils.closeQuietly(in);
77 IOUtils.closeQuietly(out);
78 }
79
80 }
81
82 protected void copyFile(InputStream in, OutputStream out)
83 throws Exception {
84 IOUtils.copy(in, out);
85 }
86
87 }
88 }