Reading PDF with DefaultStreamedContent. How to close it?

4

I have a JSF page where I generate a PDF and need to show it on the screen.

For this, I created a <p:media>

It's working, but the PDF file gets stuck (it's never closed) and over time it ends up dropping Tomcat by Many files open .

I have already tried to close FileInputStream at the end of the getStream() method, but this causes error - > Error in streaming dynamic resource. Stream Close

Does anyone have any suggestions?

xhtml:

<p:dialog>
   <p:media value="#{reportMB.stream}" player="pdf" cache="disable"/>
</p:dialog>

ManagedBean (@SessionScope):

public StreamedContent getStream(){
    StreamedContent content=null;
    FileInputStream fis=null;
    try{
        File pdf = new File("/meudiretorio/meuarquivo.pdf");
        fis = new FileInputStream(pdf);
        content=new DefaultStreamedContent(fis,"application/pdf","nomequalquer");
    }catch(IOException e){
    }
    return content;
}
    
asked by anonymous 08.04.2015 / 16:10

1 answer

2

So I found this SOen issue and see in the implementation of the class DefaultStreamedContent ", Stream is never closed by method close .

You also can not close it inside the method because it will still be read and transmitted to the user.

The solution pointed out by the same author of the above question was to copy the bytes of the file to a stream in memory, because in this way StreamedContent is not bound to the file on disk. The problem with this approach is that the file will be read all in memory.

Another option, which would not have memory-related problems, but seems to me to be a gambiarra, would be to save a reference to the original FileInputStream as an attribute of the request or session (depending on how many requests the PrimeFaces makes to retrieve the PDF) and then implement a listener to run the close at the end of the request, where PrimeFaces would have already sent the data to the user.

A third alternative would be to create a new InputStream as a wrapper for FileInputStream so that it detects the end of the file and then incovers% / p>     

08.04.2015 / 18:41