FileDonwload Primefaces 2.2RC2

2 respostas
leslie-UFT

Bom dia! Estou com problemas na lista onde tenho uma ação de editar e outra de download. Quando eu clico primeiro em download ele faz perfeitamente, mas se neste momento eu clicar em editar ele chama o download novamente. Alguém poderia me ajudar nisso. Segue o código:

View

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
		xmlns:ui="http://java.sun.com/jsf/facelets"
		xmlns:h="http://java.sun.com/jsf/html"
		xmlns:f="http://java.sun.com/jsf/core"
		xmlns:p="http://primefaces.prime.com.tr/ui">
<h:head>
    <title>:: Tcc on-line ::</title>
    <p:resources />
</h:head>
<f:view contentType="text/html">
<h:body>
    <ui:composition template="template.xhtml">
        <ui:define name="conteudo">
            <div style="width: 100%; margin-top: -30px;padding-bottom: 10px;">
                <div style="float: left;width: 70%; text-align: left;">
                 <h:form styleClass="migalha_pao">
                    <h:commandLink  action="index.jsf">
                        <h:outputText value="Principal > "/>
                    </h:commandLink>
                    <h:outputText value="Lista de Propostas" />
                </h:form>
                </div>
            </div>
            <div align="right" style="margin-top: 15px">
                <h:form>
                    <p:commandButton actionListener="#{propostaController.clear}" ajax="false"  value="Cadastrar" action="#{propostaController.formProposta}" />
                </h:form>
            </div>
            <p:messages />
            <h:panelGroup >
            <h:form id="listaPropostas" rendered="#{usuarioController.permissaoCurrente.incluir}" prependId="false">
                <p:dataTable paginator="true"  paginatorPosition="top" 
                    rows="10" paginatorTemplate="{CurrentPageReport}{PageLinks}"
                    var="objProp" value="#{propostaController.listaProposta}" emptyMessage="N&atilde;o foi encontrado registros" >
                    <p:column style="width: 400px;" headerText="Nome do Projeto">
                        <h:outputText value="#{objProp.titulo}" />
                    </p:column>
                    <p:column headerText="Cod. Turma" >
                        <h:outputText value="#{objProp.turma.codigoTurma}" />
                    </p:column>
                    <p:column headerText="Sem/Ano" >
                        <h:outputText value="#{objProp.turma.semestre}/#{objProp.turma.ano}" />
                    </p:column>
                    <p:column headerText="Situa&ccedil;&atilde;o" >
                        <h:outputText value="#{objProp.statusProposta}" />
                    </p:column>
                    <p:column>
                        <p:commandLink ajax="false"  action="#{propostaController.formPropostaEditar}" >
                            <f:setPropertyActionListener target="#{propostaController.proposta}" value="#{objProp}" />
                            <h:graphicImage value="imagens/folder_document.png" style="border: none;" alt="Editar"/>
                        </p:commandLink>
                    </p:column>
                    <p:column >
                        <p:commandLink ajax="true" title="Download">  
                            <f:setPropertyActionListener target="#{propostaController.proposta}" value="#{objProp}" />
                            <p:graphicImage value="/imagens/download.gif" />  
                            <p:fileDownload  value="#{propostaController.fileDownload}" />  
                        </p:commandLink>  
                    </p:column>
                </p:dataTable>
            </h:form>
            <script type="text/javascript">
                jQuery("#fieldcodigo").focus();
            </script>
            </h:panelGroup>
            
        </ui:define>
    </ui:composition>
</h:body>
</f:view>
</html>

Controller

package tcc.br.com.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.List;
import java.util.ResourceBundle;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.validator.ValidatorException;
import javax.servlet.ServletContext;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import tcc.br.com.dao.CursoDAO;
import tcc.br.com.dao.ProfessorDAO;
import tcc.br.com.dao.PropostaDAO;
import tcc.br.com.model.AreaAtuacao;
import tcc.br.com.model.Professor;
import tcc.br.com.model.Proposta;
import tcc.br.com.model.Usuario;
import tcc.br.com.util.ExceptionDatabase;
import tcc.br.com.validator.PropostaValidator;


/**
 *
 * @author Leslie Cardoso da Silva
 * @since  11-03-2011
 */
@ManagedBean(name="propostaController")
@SessionScoped
public class PropostaController {
    private Proposta proposta;
    private Integer ActiveTab;
    private AreaAtuacao  qryArea;
    private Professor qryProfessor;
    private List<Proposta> listaProposta;
    private Boolean enviaArquivo;
    private int BUFFER_SIZE = 8000000;
    private StreamedContent fileDownload;

    public StreamedContent getFileDownload() {
        FacesContext mensagem = FacesContext.getCurrentInstance();
        try
        {
            
            CursoDAO cDAO = new CursoDAO();
            String nome = cDAO.CursoAcademico(getProposta().getTurma());
            
            Usuario user = (Usuario)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("currentUser");
            
            File f = new File("C:\\SIGD\\upload\\"+getProposta().getTurma().getAno()+"-"+getProposta().getTurma().getSemestre()+"\\"+nome+"\\"+user.getLogin()+"\\proposta"+user.getLogin()+".pdf");
            setProposta(null);
            InputStream stream = null;
            stream = new FileInputStream(f);
            DefaultStreamedContent file = new DefaultStreamedContent(stream, "application/pdf","proposta_"+user.getLogin()+".pdf");
            
            mensagem.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,"Download da proposta realizado com sucesso!", null));
            return file;
        }
        catch (FileNotFoundException e) 
        {
           mensagem.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"Arquivo não encontrado.", null));
           return null;
        }
        catch(ExceptionDatabase e)
        {
           mensagem.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"Ocorreu um erro ao tentar fazer download da proposta.", null));
           return null;
        }
    }

    public void setFileDownload(StreamedContent fileDownload) {
        this.fileDownload = fileDownload;
    }
    
    public List<Proposta> getListaProposta() {
        if(listaProposta == null){
            FacesContext mensagem = FacesContext.getCurrentInstance();
            try
            {
                PropostaDAO pDAO = new PropostaDAO();
                Usuario user = (Usuario)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("currentUser");
                listaProposta = pDAO.listaProposta(user.getPessoa());
            }
            catch (ExceptionDatabase e) {
                mensagem.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,e.getMessage(), null));
            }
        }
        return listaProposta;
    }

    public void setListaProposta(List<Proposta> listaProposta) {
        this.listaProposta = listaProposta;
    }
    
    
   
    public void fileUploadAction(FileUploadEvent event) throws ExceptionDatabase {
        FacesContext mensagem = FacesContext.getCurrentInstance();
        
        Calendar calendar = new GregorianCalendar();  
        String newDiretory;
        String curso = new String();
        //ESSAS VARIAS É PARA SER PREENCHIDAS DA SESSAO QUE O ACADEMICO LOGOU
        Integer ano = calendar.get(Calendar.YEAR);
        Integer semestre = calendar.get(Calendar.MONTH)<7?1:2;
        
        try
        {
            CursoDAO cDAO = new CursoDAO();
            curso = cDAO.CursoAcademico(getProposta().getTurma());
        }
        catch (ExceptionDatabase e) {
            throw new ExceptionDatabase(e.getMessage());
        }    
        
        Usuario user = (Usuario)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("currentUser");
        String matricula = user.getLogin();

        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        ServletContext ctx = (ServletContext)externalContext.getContext();
        newDiretory = "C:\\SIGD\\upload\\";
        
        if(!(new File(newDiretory+ano+"-"+semestre+"\\"+curso+"\\"+matricula+"\\").exists())) {
            //new File(ctx.getRealPath("//upload//"+ano+"-"+semestre+"//"+curso+"//"+matricula+"//")).mkdirs();
           new File("C:\\SIGD\\upload\\"+ano+"-"+semestre+"\\"+curso+"\\"+matricula+"\\").mkdirs();
        }

        //File result = new File(externalContext.getRealPath("//upload//"+ano+"-"+semestre+"//"+curso+"//"+matricula)+"//"+event.getFile().getFileName());
        String ext[] = event.getFile().getFileName().split("\\.");
        File result = new File("C:\\SIGD\\upload\\"+ano+"-"+semestre+"\\"+curso+"\\"+matricula+"\\proposta"+matricula+"."+ext[1]);

        try
        {
            FileOutputStream fileOutputStream = new FileOutputStream(result);

            byte[] buffer = new byte[BUFFER_SIZE];

            int bulk;
            InputStream inputStream = event.getFile().getInputstream();
            while (true)
            {
                bulk = inputStream.read(buffer);
                if(bulk < 0){
                    break;
                }
                fileOutputStream.write(buffer, 0, bulk);
                fileOutputStream.flush();
            }

            fileOutputStream.close();
            inputStream.close();
            
            PropostaDAO pDAO = new PropostaDAO();
            pDAO.updateStatus(getProposta(), 2);

            mensagem.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,"O arquivo e a proposta foi enviado com sucesso! nome do arquivo: proposta"+matricula+"."+ext[1], null));
        } 
        catch (ExceptionDatabase e) {
            result.delete(); 
            mensagem.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,ResourceBundle.getBundle(FacesContext.getCurrentInstance().getApplication().getMessageBundle()).getString("erro.validacao.proposta.arquivo"), null));
        }
        catch(IOException e)
        {
            mensagem.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,e.getMessage(), null));
        }
    }

    public Boolean getEnviaArquivo() {
        if(enviaArquivo == null){
            enviaArquivo = Boolean.FALSE;
        }
            
        return enviaArquivo;
    }

    public void setEnviaArquivo(Boolean enviaArquivo) {
        this.enviaArquivo = enviaArquivo;
    }
    
    public String insert() {
        FacesContext mensagem = FacesContext.getCurrentInstance();
        try
        {
            PropostaValidator pVal = new PropostaValidator();
            pVal.validate(null, null, getProposta());
            
            Usuario user = (Usuario)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("currentUser");
            getProposta().getAcademico().setIdAcademico(user.getPessoa().getIdPessoa());
                    
            
            PropostaDAO pDAO = new PropostaDAO();
            pDAO.insert(getProposta());
            mensagem.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,"Proposta criada com sucesso!", null));
            setEnviaArquivo(Boolean.TRUE);
            return null;
        }
        catch (ExceptionDatabase e) {
            getProposta().setIdProposta(-1);
            mensagem.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), null));
            return null;
        }        
        catch (ValidatorException e) {
           mensagem.getMessageList().iterator();
           return null;
        }
    }
    
    public String update() {
        FacesContext mensagem = FacesContext.getCurrentInstance();
        try
        {
            PropostaValidator pVal = new PropostaValidator();
            pVal.validate(null, null, getProposta());
            
            //Usuario user = (Usuario)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("currentUser");
            //getProposta().getAcademico().setIdAcademico(user.getPessoa().getIdPessoa());
                    
            
            PropostaDAO pDAO = new PropostaDAO();
            pDAO.update(getProposta());
            mensagem.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,"Proposta atualizada com sucesso!", null));
            setEnviaArquivo(Boolean.TRUE);
            return null;
        }
        catch (ExceptionDatabase e) {
            mensagem.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), null));
            return null;
        }        
        catch (ValidatorException e) {
           mensagem.getMessageList().iterator();
           return null;
        }
    }
    
    public List<AreaAtuacao> getListaAreaProposta() {
        if(listaAreaProposta == null)
        {
            FacesContext mensagem = FacesContext.getCurrentInstance();
            try {
                PropostaDAO pDAO = new PropostaDAO();
                listaAreaProposta = pDAO.findByPropostaArea(getProposta());
                getProposta().setListaAreaAtuacao(listaAreaProposta);
            }
            catch (ExceptionDatabase e)
            {
                mensagem.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), null));
            }
        }
        return listaAreaProposta;
    }

    public void setListaAreaProposta(List<AreaAtuacao> listaAreaProposta) {
        this.listaAreaProposta = listaAreaProposta;
    }

    public Proposta getProposta() {
        if(proposta == null)
        {
            proposta = new Proposta();
        }
        return proposta;
    }

    public void setProposta(Proposta proposta) {
        this.proposta = proposta;
    }

    public String formPropostaEditar(){
        //setListaContato(null);
        //setListaAreaProfessor(null);
       
        setEnviaArquivo(Boolean.TRUE);
        setActiveTab(0);
        return "actFormProposta";
    }

    public String formProposta(){
        clear();
        setActiveTab(0);
        return "actFormProposta";
    }

    public Integer getActiveTab() {
        if(ActiveTab == null){
            ActiveTab = new Integer(0);
        }
        return ActiveTab;
    }

    public void setActiveTab(Integer ActiveTab) {
        this.ActiveTab = ActiveTab;
    }
    
   
}

2 Respostas

P

Troque

<p:commandLink ajax="true" title="Download">     
    <f:setPropertyActionListener target="#{propostaController.proposta}" value="#{objProp}" />   
    <p:graphicImage value="/imagens/download.gif" />     
    <p:fileDownload  value="#{propostaController.fileDownload}" />     
</p:commandLink>

por

<h:commandLink title="Download">     
    <f:setPropertyActionListener target="#{propostaController.proposta}" value="#{objProp}" />   
    <p:graphicImage value="/imagens/download.gif" />     
    <p:fileDownload  value="#{propostaController.fileDownload}" />     
</h:commandLink>

e seja feliz.

leslie-UFT

A primeira vez que implementei estava utilizando h:commandLink mas acontece a mesma coisa.

Criado 16 de junho de 2011
Ultima resposta 16 de jun. de 2011
Respostas 2
Participantes 2