View Javadoc

1   package org.paneris.bibliomania;
2   
3   
4   import java.io.File;
5   import java.io.FileInputStream;
6   import java.sql.Timestamp;
7   
8   import javax.servlet.ServletConfig;
9   import javax.servlet.ServletException;
10  import javax.servlet.ServletOutputStream;
11  
12  import org.melati.Melati;
13  import org.melati.poem.AccessPoemException;
14  import org.melati.poem.AccessToken;
15  import org.melati.poem.Capability;
16  import org.melati.poem.PoemTask;
17  import org.melati.poem.PoemThread;
18  import org.melati.PoemContext;
19  import org.melati.servlet.TrappedException;
20  import org.melati.template.TemplateContext;
21  import org.melati.template.TemplateEngine;
22  import org.melati.template.TemplateEngineException;
23  import org.melati.util.MelatiRuntimeException;
24  import org.melati.poem.util.StringUtils;
25  
26  
27  public class DownloadFile extends org.melati.servlet.ConfigServlet {
28  
29    /**
30     * 
31     */
32    private static final long serialVersionUID = 1L;
33    // the template engine
34    protected TemplateEngine templateEngine;
35  
36    /**
37     * Inititialise WebMacro
38     * @param config
39     */
40    public void init(ServletConfig config) throws ServletException {
41      super.init(config);
42      try {
43        templateEngine = melatiConfig.getTemplateEngine();
44        if (templateEngine != null)
45          templateEngine.init(melatiConfig);
46      } catch (TemplateEngineException e) {
47        // log it to system.err as ServletExceptions go to the
48        // servlet runner log (eg jserv.log), and don't have a stack trace!
49        e.printStackTrace(System.err);
50        throw new ServletException(e.toString());
51      }
52    }
53  
54    protected void doConfiguredRequest(final Melati melatiIn)
55      throws Exception {
56  
57      melatiIn.setTemplateEngine(templateEngine);
58      TemplateContext templateContext =
59                        templateEngine.getTemplateContext();
60      melatiIn.setTemplateContext(templateContext);
61  
62      final DownloadWrapper downloadWrapper = new DownloadWrapper();
63      try {
64        melatiIn.getDatabase().inSession (
65          AccessToken.root, new PoemTask() {
66            public void run () {
67              try {
68                Melati melati =
69                  melatiIn.getConfig().getAccessHandler().establishUser(melatiIn);
70                try {
71                  downloadWrapper.download = establishUser(melati);
72                } catch (Exception e) {
73                  handleException (melatiIn, e);
74                }
75              } catch (DownloadException e) {
76                throw (e);
77              } catch (Exception e) {
78                  error(melatiIn, e);
79                  throw new TrappedException(e);
80              }
81            }
82          }
83        );
84        
85        doDownload(melatiIn, downloadWrapper.download);
86        
87        melatiIn.getDatabase().inSession (
88          AccessToken.root, new PoemTask() {
89            public void run () {
90              try {
91                Melati melati =
92                  melatiIn.getConfig().getAccessHandler().establishUser(melatiIn);
93                try {
94                  recordDownload(melati, downloadWrapper.download);
95                } catch (Exception e) {
96                  handleException (melatiIn, e);
97                }
98              } catch (DownloadException e) {
99                throw (e);
100             } catch (Exception e) {
101                 // we have to log this here, otherwise we loose the stacktrace
102                 error(melatiIn, e);
103                 throw new TrappedException(e);
104             }
105           }
106         }
107       );
108     } catch (DownloadException e) {
109       error(melatiIn, e, downloadWrapper.download);
110     }
111   }
112 
113   public DownloadItem establishUser(Melati melati) 
114          throws AccessPoemException, DownloadException {
115     DownloadItem download = new DownloadItem();
116     BibliomaniaDatabase db = (BibliomaniaDatabase) melati.getDatabase();
117     String pathInfo = melati.getRequest().getPathInfo();
118     String filename = pathInfo.substring(pathInfo.lastIndexOf("/")+1);
119     download.filename = filename;
120     Capability registeredUser = db.getRegisteredUserCapability();
121     AccessToken token = PoemThread.accessToken();
122     if (!token.givesCapability(registeredUser)) {
123       throw new AccessPoemException(token, registeredUser);
124     } else {
125       Download document = (Download)db.getDownloadTable().getFilenameColumn().firstWhereEq(filename);
126       download.document = document;
127       if (document == null) {
128         throw new DownloadException("Sorry, the requested Document (" + filename + ") does not exist.  Please contact <a href='mailto:help@bibliomania.com'>Bibliomania.com</a> so that this problem can be corrected.");
129       } else {        
130         // check we have purchased this doc
131         if (!((User)melati.getUser()).hasPurchased(document.getTroid())) {
132           throw new DownloadException("You have not purchased the requested Document, click <a href=org.paneris.ftc365.controller.Account>here</a> to buy more Modules.");
133         } else {
134           File file = new File(db.getSettingTable().get("filepath") + filename);
135 //          File file = new File(filename);
136           download.file = file;
137           if (!file.exists()) {
138             throw new DownloadException("Sorry, the requested file (" + file.getPath() + ") has not been found, please contact mailto:help@bibliomania.com'>Bibliomania.com</a>,  so that this problem can be corrected.");
139           }
140         }
141       }
142     }
143     return download;
144   }
145   
146   public void doDownload(Melati melati, DownloadItem download) throws Exception {
147       FileInputStream filein = new FileInputStream(download.file);
148       melati.getResponse().setContentLength(new Long(download.file.length()).intValue());
149       if (download.filename.endsWith("pdf")) {
150         melati.getResponse().setContentType("application/pdf");
151       } else {
152         melati.getResponse().setContentType("application");
153       }            
154       ServletOutputStream os = melati.getResponse().getOutputStream();
155       int i = 0;
156       byte[] bbuf = new byte[10000];
157       while (i != -1) {
158         i = filein.read(bbuf, 0, 10000);
159         if (i > -1) os.write(bbuf, 0, i);
160       }
161   }
162   
163   public void recordDownload(Melati melati, DownloadItem downloaditem) {
164                                
165     BibliomaniaDatabase db = (BibliomaniaDatabase)melati.getDatabase();
166     // make record of download
167     DownloadEvent downloadEvent = (DownloadEvent)db.getDownloadEventTable()
168                                   .newPersistent();
169     downloadEvent.setUser((User)melati.getUser());
170     downloadEvent.setDocument(downloaditem.document);
171     downloadEvent.setDate(new Timestamp((new java.util.Date()).getTime()));
172     downloadEvent.getDownloadEventTable().create(downloadEvent);
173   }
174   
175   public void error(Melati melati, Exception e, DownloadItem download) {
176     try {
177       TemplateContext templateContext = melati.getTemplateContext();
178       templateContext.put("melati",melati);
179       templateContext.put("exception", e);
180       templateContext.put("download", download);
181       String templateName = "DownloadFail.wm";
182       templateEngine.expandTemplate(melati.getWriter(), 
183                                     templateName,
184                                     templateContext);
185     } catch (Exception f) {
186       f.printStackTrace(System.err);
187     }
188   }
189   
190   protected PoemContext melatiContext(Melati melati) {
191      PoemContext it = new PoemContext();
192      String[] parts = melati.getPathInfoParts();
193      if (parts.length > 0)
194       it.setMethod(StringUtils.nulled(parts[parts.length - 1]));
195     it.setLogicalDatabase("bibliomania");
196     return it;
197   }
198    
199   public String getSysAdminName() {
200     return "TimP";
201   }
202   public String getSysAdminEmail() {
203     return "timp@paneris.org";
204   }
205 
206   // default method to handle an exception withut a template engine
207   protected void handleException(Melati melati, Exception exception)
208                  throws Exception {
209 
210     if (exception instanceof AccessPoemException) {
211       melati.getConfig().getAccessHandler()
212         .handleAccessException(melati,(AccessPoemException)exception);
213     }
214     else
215       throw exception;
216   }
217 
218   public class DownloadException extends MelatiRuntimeException {
219 
220     /**
221      * 
222      */
223     private static final long serialVersionUID = 1L;
224 
225     public DownloadException(String message) {
226       super(message,null);
227     }
228   }
229   
230   private class DownloadWrapper {
231     DownloadItem download;
232   }
233   
234   private class DownloadItem {
235     String filename;
236     File file;
237     Download document;
238   }
239 
240 }