From: Winterer M. <Mar...@sc...> - 2011-09-30 06:26:40
|
Hi Brian! In my opinion there are three ways to solve your problem: 1. Ged rid of the temp file; use a in-memory solution (e.g. byte buffert) Of course, this won't work if your report builder requires a File object or if memory consumption would be too high. 2. Use a MessageBodyWriterInterceptor and delete the temp file after the body has been written: @Provider @ServerInterceptor public class TempFileRemoverInterceptor implements MessageBodyWriterInterceptor, AcceptedByMethod { public boolean accept(Class declaring, Method method) { return method.isAnnotationPresent(TempFile.class); } public void write(MessageBodyWriterContext context) throws IOException, WebApplicationException { try { context.proceed(); } finally { Object entity = context.getEntity(); if (entity instanceof File) { ((File) entity).delete(); } } } } This interceptor deletes the entity after the message body writer has been executed if the resource method is annotated with a custom "TempFile" annotation. Of course you can implement any other acception-mechanism, but make sure this interceptor only deletes files of your choice... 3. Return a special InputStream (instead of the temp file itself) that deletes the file on close: final File f = tempFile; InputStream result = new BufferedInputStream(new FileInputStream(f)) { public void close() throws IOException { super.close(); f.delete(); } }; return Response.ok(result, "application/pdf" ) .header( "Content-Disposition", "attachment; filename=" + tempFile.getName() ) .build(); Mario Von: Brian Mauter [mailto:bri...@gm...] Gesendet: Donnerstag, 29. September 2011 18:56 An: res...@li... Betreff: [?? Probable Spam] [Resteasy-developers] returning a temp file Hi, hopefully this is ridiculously simple. Google isn't being helpful though. :( Consider this: File tempFile = null; try { tempFile = File.createTempFile( "report", ".pdf" ); report.saveAsPDF( tempFile ); return Response.ok( tempFile, "application/pdf" ) .header( "Content-Disposition", "attachment; filename=" + tempFile.getName() ) .build(); } catch( Exception e ) { log.error( "Unable to get report.", e ); } finally { if ( tempFile != null ) tempFile.delete(); } Originally, I didn't have the tempFile.delete() call. I later saw my mistake and added the finally block. Now RestEasy produces a FileNotFoundException. How would you handle returning a temp file? We generate reports in our product and export them to PDF for consumption by mobile phones/tablets via RestEasy. Thanks, -Brian |