01: package com.technoetic.xplanner.actions;
02:
03: import com.technoetic.xplanner.domain.Note;
04: import com.technoetic.xplanner.file.File;
05: import net.sf.hibernate.Session;
06: import org.apache.log4j.Logger;
07: import org.apache.struts.action.ActionForm;
08: import org.apache.struts.action.ActionForward;
09: import org.apache.struts.action.ActionMapping;
10:
11: import javax.servlet.ServletOutputStream;
12: import javax.servlet.http.HttpServletRequest;
13: import javax.servlet.http.HttpServletResponse;
14: import java.io.IOException;
15: import java.io.InputStream;
16: import java.sql.SQLException;
17: import java.util.List;
18:
19: public class DownloadAttachmentAction extends AbstractAction {
20: private static Logger logger = Logger
21: .getLogger(DownloadAttachmentAction.class);
22: private static final int BUFFER_SIZE = 4000;
23:
24: protected Note locateNote(Session session, int id) {
25: Note result = null;
26:
27: try {
28: try {
29: Class objectClass = Note.class;
30: String query = "from object in class "
31: + objectClass.getName();
32: query += " where id=" + id;
33:
34: List objects = session.find(query);
35: if (objects != null && objects.size() > 0) {
36: result = (Note) objects.get(0);
37: }
38: } catch (Exception ex) {
39: logger.error("error loading objects", ex);
40: return null;
41: }
42: } catch (Exception ex) {
43: logger.error("error", ex);
44: return null;
45: }
46:
47: return result;
48: }
49:
50: protected ActionForward doExecute(ActionMapping mapping,
51: ActionForm form, HttpServletRequest request,
52: HttpServletResponse response) throws Exception {
53: int noteId = -1;
54: try {
55: noteId = Integer.parseInt(request.getParameter("oid"));
56: } catch (NumberFormatException e) {
57: logger.error("Exception: " + e.getMessage(), e);
58: }
59:
60: Note currentNote = locateNote(getSession(request), noteId);
61: if (currentNote != null) {
62: final File file = currentNote.getFile();
63: logger.debug("Note : " + file.getName());
64: logger
65: .debug("Note attachment size : "
66: + file.getFileSize());
67: logger.debug("Note contentType : " + file.getContentType());
68:
69: response.setContentType(file.getContentType());
70: response.setHeader("Content-disposition",
71: "note;filename=\"" + file.getName() + "\"");
72: response.addHeader("Content-description", file.getName());
73:
74: ServletOutputStream stream = response.getOutputStream();
75: writeAttachment(currentNote, stream);
76: stream.close();
77: }
78:
79: return null;
80: }
81:
82: private void writeAttachment(Note currentNote,
83: ServletOutputStream stream) throws SQLException,
84: IOException {
85: InputStream attachmentStream = currentNote.getFile().getData()
86: .getBinaryStream();
87: byte[] buffer = new byte[BUFFER_SIZE];
88: int n = attachmentStream.read(buffer);
89: while (n > 0) {
90: stream.write(buffer, 0, n);
91: n = attachmentStream.read(buffer);
92: }
93: stream.flush();
94: }
95: }
|