Erro ao tentar abrir PDF no browser JSF2

Boa tarde galera,

Estou a dias tentando exibir um documento PDF no browser já vi vários exemplos aqui e tomei como exemplo, porém não obtive sucesso.

É o seguinte tem uma pagina web que possui um datatable, quando clico na linha desejada aparece um dialog com o nome do arquivo o ID e um botão “Exibir documento” que é para quando o usuário clicar aparecer o documento PDF ou na mesma página ou em outra aba. Pois bem ao clicar aparece um erro, mas antes de tudo deixa eu explicar como estou procedendo desde a gravação do dado até a busca do documento.

na classe(model) tenho o seguinte código:

@Lob
    @Basic(fetch = FetchType.EAGER)
    @Column(name="arqdocumento")
    private byte[] arquivo;

Para salvar no banco de dados estou fazendo do seguinte modo:


file = new File(caminhoarquivo);
        
         byte[] bytes = new byte[(int)file.length()];
        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            try {
                fileInputStream.read(bytes);
                System.out.println("Lendo o array de bytes");
            } catch (IOException ex) {
                ex.printStackTrace();
                Logger.getLogger(F_Documento.class.getName()).log(Level.SEVERE, null, ex);
            }
            try {
                System.out.println("Encerrando a leitura");
                fileInputStream.close();
            } catch (IOException ex) {
                ex.printStackTrace();
                Logger.getLogger(F_Documento.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (FileNotFoundException ex) {
            ex.getMessage();
            Logger.getLogger(F_Documento.class.getName()).log(Level.SEVERE, null, ex);
        }

       documento.getSelectDocumento().setArquivo(bytes); // comando para inserção no banco

Para realizar a busca estou pegando com este método:


 public byte[] fileRecord(int iDdocumento){
       String hql = "SELECT d.arquivo FROM Documentos d WHERE d.codDocument= :id";
       Query consulta = HibernateUtil.getSession().createQuery(hql);
       consulta.setInteger("id", iDdocumento);
       return (byte[]) consulta.uniqueResult();
   }

E para pegar o arquivo e mostrar no browser estou fazendo um método no qual vi aqui no forum neste post http://www.guj.com.br/java/283063-jsf-2-como-exibir-um-pdf-em-nova-aba-do-browser—sem-fazer-download, porém com algumas modificações:


    public void abrirDocumentoNovaAba(String mimeContentType) throws IOException {
        
        byte [] b = documentDAO.fileRecord(selectDocumento.getCodDocument());
        DEFAULT_BUFFER_SIZE = b.length;
        

        BufferedInputStream input = null;
        BufferedOutputStream output = null;
        //File file = new File(selectDocumento.getArquivo().toString());
        System.out.println("Tamanho do Arquivo: "+DEFAULT_BUFFER_SIZE);
        try {
            // Open file.                                                                                        
            input = new BufferedInputStream(new ByteArrayInputStream(selectDocumento.getArquivo()), DEFAULT_BUFFER_SIZE);
            
            // Init servlet response.
            response.reset();
            response.setHeader("Content-Type", mimeContentType);
            response.setHeader("Content-Length", String.valueOf(selectDocumento.getArquivo().length));
            response.setHeader("Content-Disposition", "inline; filename=\"" + selectDocumento.getNomeDoArquivo() + "\"");
            output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);

            // Write file contents to response.
            byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
            int length;
            while ((length = input.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            // Finalize task.
            output.flush();
            output.close();
            input.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        facesContext.responseComplete();
    }


E está dando este erro:

javax.faces.FacesException: #{documentosFaces.abrirDOCPDF()}: java.io.FileNotFoundException: Currículo Lattes JM.pdf (Acesso negado)
	at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118)
	at javax.faces.component.UICommand.broadcast(UICommand.java:315)
	at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794)
	at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259)
	at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
	at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
	at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
	at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
	at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
	at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
	at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1002)
	at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)
	at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
	at java.lang.Thread.run(Thread.java:722)
Caused by: javax.faces.el.EvaluationException: java.io.FileNotFoundException: Currículo Lattes JM.pdf (Acesso negado)
	at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:102)
	at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
	... 26 more
Caused by: java.io.FileNotFoundException: Currículo Lattes JM.pdf (Acesso negado)
	at java.io.FileOutputStream.open(Native Method)
	at java.io.FileOutputStream.<init>(FileOutputStream.java:212)
	at java.io.FileOutputStream.<init>(FileOutputStream.java:165)
	at br.com.digitaliza.web.faces.DocumentosFaces.abrirDocumentoNovaAba(DocumentosFaces.java:112)
	at br.com.digitaliza.web.faces.DocumentosFaces.abrirDOCPDF(DocumentosFaces.java:198)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:601)
	at org.apache.el.parser.AstValue.invoke(AstValue.java:278)
	at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:274)
	at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
	at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
	... 27 more

Alguém poderia me ajudar, desde já agradeço pela ajuda!

Sem muita certeza do que vou falar.
Mas pelo erro o arquivo Currículo Lattes JM.pdf não está sendo encontrado ou está bloqueado por outra aplicação.
O pdf aparece no navegador.
Pela sua abrirDocumentoNovaAba, na linha 9 a criação do arquivo está comentada;
Veja se não é esse o problema.

Na verdade está mais por não ser encontrado, e a linha 9 foi apenas um teste sem sucesso que realizei, pois pode ver no link que disponibilizei aonde foi que eu tive uma ideia, lá pode ver que não tem essa linha.

Coloquei esse trecho de código que havia esquecido:

        FacesContext facesContext = FacesContext.getCurrentInstance();
        ExternalContext externalContext = facesContext.getExternalContext();
        HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();

Não apresentou mais o erro, porém não exibiu o documento no browser, alguem tem alguma ideia por que não apareceu?

O código ficou assim agora:


  FacesContext facesContext = FacesContext.getCurrentInstance();
        ExternalContext externalContext = facesContext.getExternalContext();
        HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
        
        byte [] b = documentDAO.fileRecord(selectDocumento.getCodDocument());
        DEFAULT_BUFFER_SIZE = b.length;
             
        BufferedInputStream input = null;
        BufferedOutputStream output = null;
      
        System.out.println("Tamanho do Arquivo: "+DEFAULT_BUFFER_SIZE);
        try {
            // Open file.                                                                                        
            input = new BufferedInputStream(new ByteArrayInputStream(selectDocumento.getArquivo()), DEFAULT_BUFFER_SIZE);
            
            // Init servlet response.
            response.reset();
            response.setHeader("Content-Type", mimeContentType);
            response.setHeader("Content-Length", String.valueOf(selectDocumento.getArquivo().length));
            response.setHeader("Content-Disposition", "inline; filename=\"" + selectDocumento.getNomeDoArquivo() + "\"");
            output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);

            // Write file contents to response.
            byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
            int length;
            while ((length = input.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            // Finalize task.
            output.flush();
            output.close();
            input.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        facesContext.responseComplete();
    }