View Javadoc
1   package fr.ifremer.quadrige3.synchro.server.components.behavior;
2   
3   /*-
4    * #%L
5    * Quadrige3 Core :: Quadrige3 Synchro server
6    * $Id:$
7    * $HeadURL:$
8    * %%
9    * Copyright (C) 2017 Ifremer
10   * %%
11   * This program is free software: you can redistribute it and/or modify
12   * it under the terms of the GNU Affero General Public License as published by
13   * the Free Software Foundation, either version 3 of the License, or
14   * (at your option) any later version.
15   * 
16   * This program is distributed in the hope that it will be useful,
17   * but WITHOUT ANY WARRANTY; without even the implied warranty of
18   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19   * GNU General Public License for more details.
20   * 
21   * You should have received a copy of the GNU Affero General Public License
22   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
23   * #L%
24   */
25  
26  
27  
28  import org.apache.commons.logging.Log;
29  import org.apache.commons.logging.LogFactory;
30  import org.apache.wicket.request.IRequestCycle;
31  import org.apache.wicket.request.IRequestHandler;
32  import org.apache.wicket.request.http.WebResponse;
33  
34  import java.io.*;
35  
36  public class FileDownloadRequestHandler implements IRequestHandler {
37  	private final Log log = LogFactory.getLog(getClass());
38  	private static final int BYTES_DOWNLOAD = 1024;
39  	private final File file;
40  	private final String fileName;
41  
42  	public FileDownloadRequestHandler(File file, String fileName) {
43  		this.file = file;
44  		this.fileName = fileName;
45  	}
46  
47  	@Override
48  	public void respond(IRequestCycle requestCycle) {
49  
50  		WebResponse response = (WebResponse) requestCycle.getResponse();
51  
52  		// do response
53  		try {
54  			response.setContentType("application/download");
55  			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
56  
57  			BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
58  			BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
59  
60  			int read;
61  			byte[] bytes = new byte[BYTES_DOWNLOAD];
62  			while ((read = in.read(bytes)) != -1) {
63  				out.write(bytes, 0, read);
64  			}
65  			out.flush();
66  			out.close();
67  			in.close();
68  		} catch (IOException e) {
69  			log.error(e.getLocalizedMessage());
70  			response.sendError(404, null);
71  		}
72  	}
73  
74  	@Override
75  	public void detach(IRequestCycle requestCycle) {
76  	}
77  
78  }