Error when using eclipse EE

Asked

Viewed 97 times

0

I’m having trouble generating image in eclipse ee - it can’t open anything and keeps giving this error:

GRAVE: Error Rendering View[/pages/produto.xhtml]
java.io.IOException: javax.el.ELException: /pages/produto.xhtml @126,69 value="#{imagemBean.foto}": Error reading 'foto' on type br.com.gomes.LojaDeVendas.bean.ImagemBean
    at org.primefaces.component.graphicimage.GraphicImageRenderer.encodeEnd(GraphicImageRenderer.java:43)
    at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:920)
    at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeRecursive(HtmlBasicRenderer.java:312)
    at com.sun.faces.renderkit.html_basic.GridRenderer.renderRow(GridRenderer.java:185)
    at com.sun.faces.renderkit.html_basic.GridRenderer.encodeChildren(GridRenderer.java:129)
    at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:890)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1856)
    at javax.faces.render.Renderer.encodeChildren(Renderer.java:176)
    at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:890)
    at org.primefaces.renderkit.CoreRenderer.renderChild(CoreRenderer.java:85)
    at org.primefaces.renderkit.CoreRenderer.renderChildren(CoreRenderer.java:72)
    at org.primefaces.component.dialog.DialogRenderer.encodeContent(DialogRenderer.java:187)
    at org.primefaces.component.dialog.DialogRenderer.encodeMarkup(DialogRenderer.java:116)
    at org.primefaces.component.dialog.DialogRenderer.encodeEnd(DialogRenderer.java:48)
    at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:920)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1863)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
    at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:458)
    at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:134)
    at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:337)
    at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:120)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:659)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:783)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:798)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1434)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)
Caused by: javax.el.ELException: /pages/produto.xhtml @126,69 value="#{imagemBean.foto}": Error reading 'foto' on type br.com.gomes.LojaDeVendas.bean.ImagemBean
    at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:114)
    at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
    at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:182)
    at javax.faces.component.UIGraphic.getValue(UIGraphic.java:149)
    at org.primefaces.component.graphicimage.GraphicImageRenderer.getImageSrc(GraphicImageRenderer.java:75)
    at org.primefaces.component.graphicimage.GraphicImageRenderer.encodeEnd(GraphicImageRenderer.java:41)
    ... 46 more
Caused by: javax.el.ELException: Error reading 'foto' on type br.com.gomes.LojaDeVendas.bean.ImagemBean
    at javax.el.BeanELResolver.getValue(BeanELResolver.java:98)
    at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
    at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
    at org.apache.el.parser.AstValue.getValue(AstValue.java:169)
    at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:184)
    at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
    ... 51 more
Caused by: java.nio.file.NoSuchFileException: C:\Desenvolvimento\Project\Uploads\branco.jpg
    at sun.nio.fs.WindowsException.translateToIOException(Unknown Source)
    at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
    at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
    at sun.nio.fs.WindowsFileSystemProvider.newByteChannel(Unknown Source)
    at java.nio.file.Files.newByteChannel(Unknown Source)
    at java.nio.file.Files.newByteChannel(Unknown Source)
    at java.nio.file.spi.FileSystemProvider.newInputStream(Unknown Source)
    at java.nio.file.Files.newInputStream(Unknown Source)
    at br.com.gomes.LojaDeVendas.bean.ImagemBean.getFoto(ImagemBean.java:35)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at javax.el.BeanELResolver.getValue(BeanELResolver.java:94)
    ... 56 more

Page:

<?xml version="1.0" encoding="UTF-8" ?>
<!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:h="http://xmlns.jcp.org/jsf/html"
    xmlns:f="http://xmlns.jcp.org/jsf/core"
    xmlns:p="http://primefaces.org/ui">
<h:head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Produtos</title>
</h:head>
<h:body>
    <p:growl id="mensagem" />

    <h:form id="formListagem">
        <p:panel header="Produtos - Listagem">
            <p:dataTable id="tabela" emptyMessage="Nenhum registro encontrado."
                paginator="true" value="#{produtoBean.produtos}" var="produto"
                rows="5">
                <f:facet name="header">
                    <p:commandButton icon="ui-icon-plus"
                        actionListener="#{produtoBean.novo}"
                        oncomplete="PF('dialogo').show();"
                        update=":mensagem :formCadastro:painel">
                        <f:actionListener
                            type="org.omnifaces.eventlistener.ResetInputAjaxActionListener" />
                    </p:commandButton>


                </f:facet>

                <p:column headerText="Descrição" filterBy="#{produto.descricao}"
                    filterMatchMode="contains" sortBy="#{produto.descricao}">
                    <h:outputText value="#{produto.descricao}" />
                </p:column>

                <p:column headerText="Quantidade" sortBy="#{produto.quantidade}">
                    <h:outputText value="#{produto.quantidade}" />
                </p:column>

                <p:column headerText="Preço" sortBy="#{produto.preco}">
                    <h:outputText value="#{produto.preco}">
                        <f:convertNumber locale="pt_BR" minFractionDigits="2" />
                    </h:outputText>
                </p:column>

                <p:column headerText="Fabricante"
                    filterBy="#{produto.fabricante.descricao}"
                    filterMatchMode="contains" sortBy="#{produto.fabricante.descricao}">
                    <h:outputText value="#{produto.fabricante.descricao}" />
                </p:column>

                <p:column headerText="Opções">
                    <p:commandButton icon="ui-icon-trash"
                        actionListener="#{produtoBean.excluir}"
                        update=":mensagem :formListagem:tabela">
                        <p:confirm header="Confirmação"
                            message="Deseja excluir o produto?" icon="ui-icon-alert" />
                        <f:attribute name="produtoSelecionado" value="#{produto}" />
                    </p:commandButton>

                    <p:commandButton icon="ui-icon-pencil"
                        actionListener="#{produtoBean.editar}"
                        update=":mensagem :formCadastro:painel"
                        oncomplete="PF('dialogo').show();">
                        <f:attribute name="produtoSelecionado" value="#{produto}" />
                        <f:actionListener
                            type="org.omnifaces.eventlistener.ResetInputAjaxActionListener" />
                    </p:commandButton>
                </p:column>
            </p:dataTable>

            <p:confirmDialog global="true">
                <p:commandButton value="Sim" type="button"
                    styleClass="ui-confirmdialog-yes" icon="ui-icon-check" />
                <p:commandButton value="Não" type="button"
                    styleClass="ui-confirmdialog-no" icon="ui-icon-close" />
            </p:confirmDialog>
        </p:panel>
    </h:form>

    <p:dialog header="Produtos - Cadastro" widgetVar="dialogo"
        draggable="false" resizable="false" modal="true" closable="false">
        <h:form id="formCadastro" enctype="multipart/form-data">
            <h:panelGrid id="painel" columns="2">
                <p:outputLabel for="descricao" value="Descrição:" />
                <p:inputText id="descricao" maxlength="50" size="30"
                    value="#{produtoBean.produto.descricao}" required="true"
                    requiredMessage="O campo 'Descrição' é obrigatório" />

                <p:outputLabel for="quantidade" value="Quantidade:" />
                <p:inputText id="quantidade" maxlength="5" size="10"
                    value="#{produtoBean.produto.quantidade}" required="true"
                    requiredMessage="O campo 'Quantidade' é obrigatório"
                    converterMessage="Informe um valor válido para o campo 'Quantidade'"
                    validatorMessage="Informe um valor entre 0 e 1000 para o campo 'Quantidade'">
                    <f:validateLongRange minimum="0" maximum="1000" />
                </p:inputText>

                <p:outputLabel for="preco" value="Preço:" />
                <p:inputText id="preco" maxlength="7" size="10"
                    value="#{produtoBean.produto.preco}" required="true"
                    requiredMessage="O campo 'Preço' é obrigatório"
                    converterMessage="Informe um valor válido para o campo 'Preço''"
                    validatorMessage="Informe um valor entre 0,01 e 9999,99 para o campo 'Preço'">
                    <f:validateDoubleRange minimum="0.01" maximum="9999.99" />
                    <f:convertNumber locale="pt_BR" minFractionDigits="2" />
                </p:inputText>

                <p:outputLabel for="fabricante" value="Fabricante:" />
                <p:selectOneMenu id="fabricante" filter="true"
                    value="#{produtoBean.produto.fabricante}"
                    converter="omnifaces.SelectItemsConverter" required="true"
                    requiredMessage="O campo 'Fabricante' é obrigatório">
                    <f:selectItem noSelectionOption="true"
                        itemLabel="Selecione um fabricante" />
                    <f:selectItems value="#{produtoBean.fabricantes}" var="fabricante"
                        itemValue="#{fabricante}" itemLabel="#{fabricante.descricao}" />
                </p:selectOneMenu>

                <p:outputLabel for="upload" value="Upload:" />
                <p:fileUpload id="upload" mode="advanced"
                    fileUploadListener="#{produtoBean.upload}"
                    update=":mensagem :formCadastro:foto" auto="true" />

               <p:outputLabel for="foto" value="Foto: " />
               <p:graphicImage id="foto" value="#{imagemBean.foto}">
                  <f:param name="caminho" value="#{produtoBean.produto.caminho}" />
               </p:graphicImage>

            </h:panelGrid>

            <h:panelGrid columns="2">
                <p:commandButton value="Salvar"
                    actionListener="#{produtoBean.salvar}"
                    update=":mensagem :formCadastro:painel :formListagem:tabela" />
                <p:commandButton value="Fechar" oncomplete="PF('dialogo').hide();" />
            </h:panelGrid>
        </h:form>
    </p:dialog>
</h:body>
</html>

Imagembean class:

package br.com.gomes.LojaDeVendas.bean;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;

import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;

@ManagedBean
@RequestScoped
public class ImagemBean {
    @ManagedProperty("#{param.caminho}")
    private String caminho;

    private StreamedContent foto;

    public String getCaminho() {
        return caminho;
    }

    public void setCaminho(String caminho) {
        this.caminho = caminho;
    }

    public StreamedContent getFoto() throws IOException {
        if(caminho == null || caminho.isEmpty()){
            Path path = Paths.get("C:/Desenvolvimento/Project/Uploads/branco.jpg");
            InputStream stream = Files.newInputStream(path);
            foto = new DefaultStreamedContent(stream);
        }else{
            Path path = Paths.get(caminho);
            InputStream stream = Files.newInputStream(path);
            foto = new DefaultStreamedContent(stream);
        }
        return foto;
    }

    public void setFoto(StreamedContent foto) {
        this.foto = foto;
    }
}

1 answer

0


The problem seems to be in getFoto(), try doing something like this:

public StreamedContent getFoto() {
    FacesContext fc = FacesContext.getCurrentInstance();
    if (fc.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
       return new DefaultStreamedContent();
    } else {
       String caminho = context.getExternalContext().getRequestParameterMap().get("caminho");
       return new DefaultStreamedContent(new FileInputStream(new File(caminho));
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.