Problem loading database image with JSF

Asked

Viewed 714 times

5

I’m having a problem loading images from the database with JSF and CDI, below is the code for a better understanding of the problem.

<ui:define name="titulo">Detalhes Anuncio</ui:define>

<ui:define name="corpo">

  <div class="jumbotron" style="margin-top: 15px;">
        <div class="row">
            <div class="col-lg-12">


                <h3> <i class="fa fa-building fa-1x"></i> Detalhes Anuncios </h3>

                <h:form>
                    <p:dataTable id="anunciosCad" var="anuncio" value="#{anuncioMB.listAnuncios}" paginator="true" rows="10" 
                                paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}" 
                                rowsPerPageTemplate="5,10,15" paginatorPosition="bottom" styleClass="table table-hover">

                        <p:column headerText="Anuncio Imagem" style="text-align: center;">
                            <p:graphicImage height="100" width="160" value="#{imagemMB.anuncioImagem}" styleClass="#{anuncio.id}" binding="#{imagemMB.graphicImage}" />
                        </p:column>

                        <p:column headerText="Id" sortBy="#{anuncio.id}" width="60" style="text-align: center;">
                            <h:outputText value="#{anuncio.id}" />
                        </p:column>
                        <p:column headerText="Nome">
                            <h:outputText value="#{anuncio.nome}" />
                        </p:column>
                        <p:column headerText="Valor">
                            <h:outputText value="#{anuncio.valor}"> 
                                <f:convertNumber locale="pt_BR" maxFractionDigits="2" minFractionDigits="2" />
                            </h:outputText>
                        </p:column>
                        <p:column headerText="Descrição">
                            <h:outputText value="#{anuncio.descricao}" />
                        </p:column>

                        <p:column width="60" style="text-align: center;">
                             <p:commandButton update=":form:anuncioDetail" oncomplete="PF('anuncioDialog').show()" icon="ui-icon-search" title="View">
                                <f:setPropertyActionListener value="#{anuncio}" target="#{anuncioMB.anuncioSelected}" />
                            </p:commandButton>
                        </p:column>

                    </p:dataTable>

                </h:form>

                <h:form id="form">

                    <p:dialog header="Atualizar Anuncio" widgetVar="anuncioDialog" modal="true">
                        <p:outputPanel id="anuncioDetail">

                            <p:messages showDetail="true" closable="true"/>
                            <p:separator/>

                            <div class="form-group">
                                <label for="nome">Nome:</label>
                                <p:inputText styleClass="form-control" placeholder="informe o nome..." required="true" id="nome" value="#{anuncioMB.anuncioSelected.nome}"/>
                            </div>

                            <div class="form-group">
                                <label for="valor">Valor:</label>
                                <p:inputText styleClass="form-control" placeholder="informe o valor..." required="true" id="valor" size="12" value="#{anuncioMB.anuncioSelected.valor}">
                                    <f:convertNumber locale="pt_BR" maxFractionDigits="2" minFractionDigits="2" />
                                </p:inputText>
                            </div>

                            <div class="form-group">
                                <label for="descricao">Descrição:</label> 
                                <h:outputLink value="#" id="infoDescricao"> <p:spacer width="10"/> <i class="fa fa-exclamation"></i></h:outputLink>
                                <p:tooltip value="Por favor informe uma descrição para o anuncio..." for="infoDescricao"/>

                                <p:inputTextarea id="descricao" required="true" styleClass="form-control" value="#{anuncioMB.anuncioSelected.descricao}"/>
                            </div>  

                            <div class="form-group">
                                <h:commandButton value="Atualizar Anuncio" styleClass="btn btn-lg btn-primary btn-block" action="#{anuncioMB.atualizarAnuncio}"/>
                            </div>  

                        </p:outputPanel>
                    </p:dialog> 

                </h:form>



            </div>
        </div>

  </div>

</ui:define>        

And my Managedben is as follows:

package br.com.comparison.shoop.managedBeans;

import java.io.ByteArrayInputStream;
import java.io.Serializable;

import javax.enterprise.context.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseId;
import javax.inject.Inject;
import javax.inject.Named;

import org.primefaces.component.graphicimage.GraphicImage;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;

@Named
@SessionScoped
public class ImagemMB implements Serializable{



/**
 * 
 */
private static final long serialVersionUID = 2583851912673523505L;



@Inject
private AnuncioMB anuncioMB;

private GraphicImage graphicImage;

public GraphicImage getGraphicImage() {
    return graphicImage;
}
public void setGraphicImage(GraphicImage graphicImage) {
    this.graphicImage = graphicImage;
}


public StreamedContent getAnuncioImagem(){
    FacesContext context = FacesContext.getCurrentInstance();

    if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
        return new DefaultStreamedContent();
    }

    int id = 8;
    return new DefaultStreamedContent( new ByteArrayInputStream( anuncioMB.getMapAnuncios().get(id).getImagem() ) );
}

}

Detail: the Managedbean that loads the listing of advertisements is like @Named and @Viewscoped I use Imagemmb only to dynamically load the images.

Thus:

package br.com.comparison.shoop.managedBeans;

import java.io.IOException;
import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;

import org.apache.commons.io.IOUtils;
import org.primefaces.model.UploadedFile;

import br.com.comparison.shoop.entity.Anuncio;
import br.com.comparison.shoop.service.AnuncioService;

@Named
@ViewScoped
public class AnuncioMB implements Serializable{


/**
 * 
 */
private static final long serialVersionUID = 8900844371010166277L;


private Anuncio anuncio;
private Anuncio anuncioSelected;
private UploadedFile file;
private List<Anuncio> anuncios;
private Map<Integer, Anuncio> mapAnuncios;


@Inject
private UsuarioMB usuarioMB;

@Inject
private AnuncioService anuncioService;

public Anuncio getAnuncio() {
    return anuncio;
}

public void setAnuncio(Anuncio anuncio) {
    this.anuncio = anuncio;
}
public UploadedFile getFile() {
    return file;
}

public void setFile(UploadedFile file) {
    this.file = file;
}

public List<Anuncio> getAnuncios() {
    return anuncios;
}

public void setAnuncios(List<Anuncio> anuncios) {
    this.anuncios = anuncios;
}

public Anuncio getAnuncioSelected() {
    return anuncioSelected;
}

public void setAnuncioSelected(Anuncio anuncioSelected) {
    this.anuncioSelected = anuncioSelected;
}

public Map<Integer, Anuncio> getMapAnuncios() {
    return mapAnuncios;
}





@PostConstruct
public void init(){

    if (anuncio == null) {
        anuncio = new Anuncio();
    }

    if (anuncioSelected == null) {
        anuncioSelected = new Anuncio();
    }

}


public String salvarAnuncio() throws IOException{

    anuncio.setImagem(IOUtils.toByteArray(file.getInputstream()));
    anuncio.setEmpresa(usuarioMB.getUserSession().getEmpresa());
    anuncio.setDataCadastro( new Date() );

    anuncioService.salvar(anuncio);

    return "detalhes-anuncio";
}

public String atualizarAnuncio(){

    if (anuncioSelected == null) {
        throw new IllegalArgumentException("Nao localizou este anuncio");
    }

    anuncioService.update(anuncioSelected);

    return "detalhes-anuncio";
}


public List<Anuncio> getListAnuncios(){

    if (anuncios == null) {
        anuncios = anuncioService.list();

        mapAnuncios = new HashMap<Integer, Anuncio>(0);

        for (Anuncio a : anuncios) {
            mapAnuncios.put(a.getId(), a);
        }

    }

    return anuncios;
}


/*  public StreamedContent getImagen(){
    return new DefaultStreamedContent( new ByteArrayInputStream( mapAnuncios.get(8).getImagem() ),"image/jpg" );
}*/


}

When I call the page to list the advertisements the following error occurs:

Apr 28, 2015 6:18:38 PM org.primefaces.application.resource.Streamedcontenthandler Handle SEVERE: Error in streaming Dynamic Resource. Error Reading 'anuncioImage' on type br.com.comparison.shoop.managedBeans.Imagemmb Apr 28, 2015 6:18:38 PM org.apache.Catalina.core.Standardwrappervalve invoke SEVERE: Servlet.service() for Servlet [Faces Servlet] in context with path [/comparison-shopp] threw Exception java.io.Ioexception: javax.el.Elexception: Error Reading 'anuncioImage' on type br.com.comparison.shoop.managedBeans.Imagemmb at org.primefaces.application.resource.Streamedcontenthandler.Handle(Streamedcontenthandler.java:78) at org.primefaces.application.resource.Primeresourcehandler.handleResourceRequest(Primeresourcehandler.java:72) at javax.faces.webapp.FacesServlet.service(Facesservlet.java:643) at org.apache.Catalina.core.Applicationfilterchain.internalDoFilter(Applicationfilterchain.java:304) at org.apache.Catalina.core.Applicationfilterchain.doFilter(Applicationfilterchain.java:210) at br.com.comparison.shoop.filtros.AutorizacaoFilter.doFilter(Authorizecaofilter.java:37) 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:240) at org.apache.Catalina.core.Standardcontextvalve.invoke(Standardcontextvalve.java:164) at org.apache.Catalina.authenticator.Authenticatorbase.invoke(Authenticatorbase.java:462) at org.apache.Catalina.core.Standardhostvalve.invoke(Standardhostvalve.java:164) at org.apache.Catalina.valves.Errorreportvalve.invoke(Errorreportvalve.java:100) at org.apache.Catalina.valves.Accesslogvalve.invoke(Accesslogvalve.java:562) at org.apache.Catalina.core.Standardenginevalve.invoke(Standardenginevalve.java:118) at org.apache.Catalina.connector.Coyoteadapter.service(Coyoteadapter.java:395) at org.apache.Coyote.http11.Http11processor.process(Http11processor.java:250) at org.apache.Coyote.http11.Http11protocol$Http11connectionhandler.process(Http11protocol.java:188) at org.apache.Tomcat.util.net.Jioendpoint$Socketprocessor.run(Jioendpoint.java:302) at java.util.Concurrent.ThreadPoolExecutor.runWorker(Threadpoolexecutor.java:1145) at java.util.Concurrent.Threadpoolexecutor$Worker.run(Threadpoolexecutor.java:615) at java.lang.Thread.run(Thread.java:745) Caused by: javax.el.Elexception: Error Reading 'anuncioImage' on type br.com.comparison.shoop.managedBeans.Imagemmb at javax.el.Beanelresolver.getValue(Beanelresolver.java:91) at com.sun.faces.el.Demuxcompositeelsolve.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:189) at org.jboss.Weld.el.Weldvalueexpression.getValue(Weldvalueexpression.java:50) at org.primefaces.application.resource.Streamedcontenthandler.Handle(Streamedcontenthandler.java:53) ... 21 more Caused by: org.jboss.Weld.context.Contextnotactiveexception: WELD-001303: No active contexts for Scope type javax.faces.view.Viewscoped at org.jboss.Weld.manager.Beanmanagerimpl.getcontext(Beanmanagerimpl.java:691) at org.jboss.Weld.bean.proxy.ContextBeanInstance.getInstance(Contextbeaninstance.java:79) at org.jboss.Weld.bean.proxy.ProxyMethodHandler.getInstance(Proxymethodhandler.java:125) at br.com.comparison.shoop.managedBeans.Anunciomb$Proxy$$$_Weldclientproxy.getMapAnuncios(Unknown Source) at br.com.comparison.shoop.managedBeans.ImagemMB.getAnuncioImage(Imagemmb.java:50) 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:606) at javax.el.Beanelresolver.getValue(Beanelresolver.java:87) ... 27 more

I’d like to understand where I’m going wrong. I know this process doesn’t work for @Viewscoped, so I created a managedBean just to load the image from the bank.

  • This link might be of interest to you: http://stackoverflow.com/questions/10073905/display-database-blob-images-in-pgraphicimage-inside-uirepeat

  • I don’t understand your use of "Binding" in the "graphicImage" component. What do you need it for? Have you tried removing "Binding" and leaving only "value"? The use of value seems correct.

No answers

Browser other questions tagged

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