Problema com p:graphicImage

0 respostas
pix

A dúvida agora é exibir as imagens ao clicar no commandButton, se alguém puder auxiliar, as fotos simplesmente não aparecem.

Entidade
import java.io.Serializable;

import javax.persistence.*;

@Entity
@Table(name = "Produto")
@NamedQueries({
    @NamedQuery(name = "produto.findAll", query = "SELECT p FROM Produto p"),
    @NamedQuery(name = "produto.findCodigo", query = "SELECT p FROM Produto p WHERE p.id = :id"),
    @NamedQuery(name = "produto.count", query = "SELECT COUNT(p) FROM Produto p")})
public class Produto implements Serializable {

    private static final long serialVersionUID = 1L;
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "idproduto")
    private int id;
    @Column(name = "nome")
    private String nome;
    @Column(name = "undmed")
    private String undmed;
    @Column(name = "foto")
    private String foto;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    /**
     * @return the nome
     */
    public String getNome() {
        return nome;
    }

    /**
     * @param nome the nome to set
     */
    public void setNome(String nome) {
        this.nome = nome;
    }

    /**
     * @return the undmed
     */
    public String getUndmed() {
        return undmed;
    }

    /**
     * @param undmed the undmed to set
     */
    public void setUndmed(String undmed) {
        this.undmed = undmed;
    }

    /**
     * @return the foto
     */
    public String getFoto() {
        return foto;
    }

    /**
     * @param foto the foto to set
     */
    public void setFoto(String foto) {
        this.foto = foto;
    }

}
Bean
import entities.Produto;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
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.persistence.EntityManager;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.primefaces.model.UploadedFile;
import repository.ProdutoRepository;

/**
 *
 * @author daniel
 */
@ManagedBean(name = "mbProduto")
@SessionScoped
public class ProdutoBean implements java.io.Serializable {

    private Produto produto = new Produto();
    private List<Produto> produtos;
    private List<Produto> fotoProdutos;
    private UploadedFile file;

    public void send() throws IOException {
        if (getFile() != null) {
            FacesMessage msg = new FacesMessage("Arquivo", getFile().getFileName() + " enviado.");
            upload(getFile().getFileName(), getFile().getInputstream());
            FacesContext.getCurrentInstance().addMessage(null, msg);
            produto.setFoto(getFile().getFileName());
            this.save();
        }

    }

    public void save() throws IOException {
        ProdutoRepository produtoRepository = new ProdutoRepository(this.getManager());
        produtoRepository.save(this.produto);

        this.produto = new Produto();
        //this.produtos = null;  
        FacesContext.getCurrentInstance().getExternalContext().redirect("produto.xhtml");
    }

    public void upload(String fileName, InputStream in) {
        try {
            FacesContext aFacesContext = FacesContext.getCurrentInstance();
            ServletContext context = (ServletContext) aFacesContext.getExternalContext().getContext();
            String realPath = context.getRealPath("/");
            String diretorioDestino = realPath + "/fotos/";

            OutputStream out = new FileOutputStream(new File(diretorioDestino + fileName));
            int reader = 0;
            byte[] bytes = new byte[(int) getFile().getSize()];
            try {
                while ((reader = in.read(bytes)) != -1) {
                    out.write(bytes, 0, reader);
                }
                in.close();
                out.flush();
                out.close();
            } catch (IOException ex) {
                Logger.getLogger(ProdutoBean.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(ProdutoBean.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public String preparaAlterar(Produto produto) throws IOException {
        this.setProduto(produto);
        FacesContext.getCurrentInstance().getExternalContext().redirect("alterar.xhtml");
        return "alterar.xhtml?faces-redirect=true";
    }

    public void update() throws IOException {
        ProdutoRepository produtoRepository = new ProdutoRepository(this.getManager());
        produtoRepository.update(this.produto);


        this.produto = new Produto();
        this.produtos = null;
        FacesContext.getCurrentInstance().getExternalContext().redirect("listagem.xhtml");
    }

    public void remove(Produto produto) {
        ProdutoRepository repository = new ProdutoRepository(this.getManager());
        repository.remove(produto);

        this.produtos = null;
    }

    public List<Produto> getProdutos() {
        if (this.produtos == null) {
            ProdutoRepository repository = new ProdutoRepository(this.getManager());
            this.produtos = repository.getProduto();
        }

        return this.produtos;
    }

    public List<Produto> getProdutosCodigo() {
        if (this.fotoProdutos == null) {
            ProdutoRepository repository = new ProdutoRepository(this.getManager());
            this.fotoProdutos = repository.getProdutoCodigo(produto.getId());
        }

        return this.fotoProdutos;
    }

    public Produto getProduto() {
        return produto;
    }

    public void setProduto(Produto produto) {
        this.produto = produto;
    }

    private EntityManager getManager() {
        FacesContext fc = FacesContext.getCurrentInstance();
        ExternalContext ec = fc.getExternalContext();
        HttpServletRequest request = (HttpServletRequest) ec.getRequest();
        return (EntityManager) request.getAttribute("entityManager");
    }

    /**
     * @return the file
     */
    public UploadedFile getFile() {
        return file;
    }

    /**
     * @param file the file to set
     */
    public void setFile(UploadedFile file) {
        this.file = file;
    }
}
Repository
import entities.Produto;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;

/**
 *
 * @author daniel
 */
public class ProdutoRepository implements Serializable {

    private EntityManager entityManager;

    public ProdutoRepository(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    public void save(Produto produto) {
        this.entityManager.persist(produto);
        this.entityManager.flush();
    }

    public void remove(Produto produto) {
        Produto produtoTemp = new Produto();
        produtoTemp = this.entityManager.find(Produto.class, produto.getId());

        this.entityManager.remove(produto);

    }

    public void update(Produto produto) {
        this.entityManager.merge(produto);
        this.entityManager.flush();
    }

    @SuppressWarnings("unchecked")
    public List<Produto> getProduto() {
        return this.entityManager.createNamedQuery("produto.findAll")
                .getResultList();
    }
    
    @SuppressWarnings("unchecked")
    public List<Produto> getProdutoCodigo(int id) {
        return this.entityManager.createNamedQuery("produto.findCodigo")
                .setParameter("id", id)
                .getResultList();
    }
    
     public Produto search(int ID) {
        return this.entityManager.find(Produto.class, ID);
    }
}
JSF
<?xml version='1.0' encoding='ISO-8859-1' ?>   
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:p="http://primefaces.org/ui"
      xmlns:ui="http://xmlns.jcp.org/jsf/facelets">

    <f:view>
        <h:head>
            <title>Tipo de Lista</title>

            <style type="text/css">
                .ui-widget {font-size: 12px !important;}
            </style>

        </h:head>
        <h:body>
            <ui:include src="../menu.xhtml" />
            <h:form id="frmGeral">
                <p:fieldset legend="Lista de Compras" toggleable="true">
                    <p:messages id="messages" />

                    <h:panelGrid columns="2" style="font-family: Verdana, Arial; font-weight: bold;">
                        <p:dataTable id="itListas" emptyMessage="Itens já comprados."
                                     value="#{itemListaBean.itListas}" var="it"
                                     style="text-align: center; font-weight: bold;">
                            <f:facet name="header">
                                <h:outputText value="Itens da Lista de Compras" />
                            </f:facet>

                            <p:column>
                                <f:facet name="header">
                                    <h:outputText value="Produto" />
                                </f:facet>
                                <h:outputText value="#{it.produto.nome}" />
                            </p:column>

                            <p:column>
                                <f:facet name="header">
                                    <h:outputText value="Quantidade" />
                                </f:facet>
                                <h:outputText value="#{it.quantidade}">
                                    <f:convertNumber type="number"/>  
                                </h:outputText>
                            </p:column>

                            <p:column>
                                <f:facet name="header">
                                    <h:outputText value="Valor" />
                                </f:facet>
                                <h:outputText value="#{it.valor}">
                                    <f:convertNumber type="currency"/>  
                                </h:outputText>
                            </p:column>

                            <p:column>
                                <f:facet name="header">
                                    <h:outputText value="Total" />
                                </f:facet>
                                <h:outputText value="#{it.valor * it.quantidade}">
                                    <f:convertNumber type="currency"/>  
                                </h:outputText>
                            </p:column>

                            <p:column>
                                <f:facet name="header">
                                    <h:outputText value="Foto" />
                                </f:facet>

                                <p:commandButton id="addButton" update=":frmGeral:infoProduto"
                                                 oncomplete="produtoDialog.show()" icon="ui-icon-plus"
                                                 title="Adicionar imagens">
                                    <f:setPropertyActionListener value="#{it.produto}" target="#{mbProduto.produto}" />
                                </p:commandButton>

                            </p:column>

                            <p:column>
                                <f:facet name="header">
                                    <h:outputText value="Comprar"/>
                                </f:facet>
                                <f:ajax event="click"  render="@form" listener="#{itemListaBean.comprar(it)}">
                                    <h:commandLink value="Comprar"/>
                                </f:ajax>
                            </p:column>
                            <p:column>
                                <f:facet name="header">
                                    <h:outputText value="Remover"/>
                                </f:facet>
                                <f:ajax event="click" render="@form" listener="#{itemListaBean.remove(it)}">
                                    <h:commandLink value="Remover"/>
                                </f:ajax>
                            </p:column>

                            <p:columnGroup type="footer">  
                                <p:row>  
                                    <p:column colspan="3" footerText="Totais:"  
                                              style="text-align:right"  />  

                                    <p:column footerText="#{itemListaBean.total}" />  
                                    <p:column colspan="3" footerText="" />  
                                </p:row>  
                            </p:columnGroup>  
                            <f:facet name="footer">
                                <h:outputText
                                    value="Há um total de #{itemListaBean.getCount()} produto(s) não comprado(s)." />
                            </f:facet>
                        </p:dataTable>
                    </h:panelGrid>
                </p:fieldset>
                <p:dialog header="Detalhes do produto" widgetVar="produtoDialog"
                          resizable="false" id="produtoDlg" showEffect="fade"
                          hideEffect="explode" modal="true" draggable="true" maximizable="true"
                          minimizable="true">

                    <h:panelGrid id="infoProduto" columns="2" style="margin:0 auto;">

                        <p:galleria var="f" value="#{mbProduto.produtos}" effect="slide"
                                    effectSpeed="100" panelHeight="250" panelWidth="500"
                                    frameHeight="70" frameWidth="160">

                            <p:graphicImage value="/fotos/#{f.foto}" />

                        </p:galleria>

                    </h:panelGrid>
                </p:dialog>
            </h:form>
        </h:body>
    </f:view>
</html>
Criado 21 de setembro de 2013
Respostas 0
Participantes 1