1
resposta

Erro ao filtrar por preço

Ao filtrar livros pelo preço, estou recebendo o erro abaixo. Infelizmente não consegui descobrir sua causa. Agradeço quem puder me ajudar. O código não chega a executar a função precoEhMenor.

fev 21, 2017 11:18:46 AM com.sun.faces.application.view.FaceletViewHandlingStrategy handleRenderException
GRAVE: Error Rendering View[/livro.xhtml]
javax.el.ELException: /livro.xhtml @116,72 filterFunction="livroBean.precoEhMenor": Cannot convert livroBean.precoEhMenor of type class java.lang.String to class java.lang.Integer
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(Unknown Source)
    at org.primefaces.component.datatable.feature.FilterFeature.filter(FilterFeature.java:171)
    at org.primefaces.component.datatable.feature.FilterFeature.encode(FilterFeature.java:120)
    at org.primefaces.component.datatable.DataTableRenderer.encodeEnd(DataTableRenderer.java:80)
    at javax.faces.component.UIComponentBase.encodeEnd(Unknown Source)
    at javax.faces.component.UIComponent.encodeAll(Unknown Source)
    at com.sun.faces.context.PartialViewContextImpl$PhaseAwareVisitCallback.visit(Unknown Source)
    at com.sun.faces.component.visit.PartialVisitContext.invokeVisitCallback(Unknown Source)
    at org.primefaces.component.api.UIData.visitTree(UIData.java:827)
    at javax.faces.component.UIComponent.visitTree(Unknown Source)
    at javax.faces.component.UIForm.visitTree(Unknown Source)
    at javax.faces.component.UIComponent.visitTree(Unknown Source)
    at javax.faces.component.UIComponent.visitTree(Unknown Source)
    at com.sun.faces.context.PartialViewContextImpl.processComponents(Unknown Source)
    at com.sun.faces.context.PartialViewContextImpl.processPartial(Unknown Source)
    at org.primefaces.context.PrimePartialViewContext.processPartial(PrimePartialViewContext.java:57)
    at javax.faces.component.UIViewRoot.encodeChildren(Unknown Source)
    at javax.faces.component.UIComponent.encodeAll(Unknown Source)
    at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(Unknown Source)
    at com.sun.faces.application.view.MultiViewHandler.renderView(Unknown Source)
    at com.sun.faces.lifecycle.RenderResponsePhase.execute(Unknown Source)
    at com.sun.faces.lifecycle.Phase.doPhase(Unknown Source)
    at com.sun.faces.lifecycle.LifecycleImpl.render(Unknown Source)
    at javax.faces.webapp.FacesServlet.service(Unknown Source)
    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:53)
    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:199)
    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:495)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:767)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1347)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

fev 21, 2017 11:18:46 AM com.sun.faces.context.AjaxExceptionHandlerImpl handlePartialResponseError
GRAVE: javax.el.ELException: /livro.xhtml @116,72 filterFunction="livroBean.precoEhMenor": Cannot convert livroBean.precoEhMenor of type class java.lang.String to class java.lang.Integer
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(Unknown Source)
    at org.primefaces.component.datatable.feature.FilterFeature.filter(FilterFeature.java:171)
    at org.primefaces.component.datatable.feature.FilterFeature.encode(FilterFeature.java:120)
    at org.primefaces.component.datatable.DataTableRenderer.encodeEnd(DataTableRenderer.java:80)
    at javax.faces.component.UIComponentBase.encodeEnd(Unknown Source)
    at javax.faces.component.UIComponent.encodeAll(Unknown Source)
    at com.sun.faces.context.PartialViewContextImpl$PhaseAwareVisitCallback.visit(Unknown Source)
    at com.sun.faces.component.visit.PartialVisitContext.invokeVisitCallback(Unknown Source)
    at org.primefaces.component.api.UIData.visitTree(UIData.java:827)
    at javax.faces.component.UIComponent.visitTree(Unknown Source)
    at javax.faces.component.UIForm.visitTree(Unknown Source)
    at javax.faces.component.UIComponent.visitTree(Unknown Source)
    at javax.faces.component.UIComponent.visitTree(Unknown Source)
    at com.sun.faces.context.PartialViewContextImpl.processComponents(Unknown Source)
    at com.sun.faces.context.PartialViewContextImpl.processPartial(Unknown Source)
    at org.primefaces.context.PrimePartialViewContext.processPartial(PrimePartialViewContext.java:57)
    at javax.faces.component.UIViewRoot.encodeChildren(Unknown Source)
    at javax.faces.component.UIComponent.encodeAll(Unknown Source)
    at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(Unknown Source)
    at com.sun.faces.application.view.MultiViewHandler.renderView(Unknown Source)
    at com.sun.faces.lifecycle.RenderResponsePhase.execute(Unknown Source)
    at com.sun.faces.lifecycle.Phase.doPhase(Unknown Source)
    at com.sun.faces.lifecycle.LifecycleImpl.render(Unknown Source)
    at javax.faces.webapp.FacesServlet.service(Unknown Source)
    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:53)
    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:199)
    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:495)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:767)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1347)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

Abaixo o código do método

public boolean precoEhMenor(Object valorColuna, Object filtroDigitado, Locale locate) {

        // tirando espaços do filtro
        String textoDigitado = (filtroDigitado == null) ? null : filtroDigitado.toString().trim();

        System.out.println("Filtrando pelo " + textoDigitado + ", Valor do elemento: " + valorColuna);

        // o filtro é nulo ou vazio?
        if (textoDigitado == null || textoDigitado.equals("")) {
            return true;
        }

        // elemento da tabela é nulo?
        if (valorColuna == null) {
            return false;
        }

        try {
            // fazendo o parsing do filtro para converter para Double
            Double precoDigitado = Double.valueOf(textoDigitado);
            Double precoColuna = (Double) valorColuna;

            // comparando os valores, compareTo devolve um valor negativo se o
            // value é menor do que o filtro
            return precoColuna.compareTo(precoDigitado) < 0;

        } catch (NumberFormatException e) {

            // usuario nao digitou um numero
            return false;
        }
    }

Abaixo a página livro.xhtml

<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:ui="http://xmlns.jcp.org/jsf/facelets"
    xmlns:p="http://primefaces.org/ui">

<ui:composition template="_template.xhtml">
    <f:metadata>
        <f:viewParam name="livroId" value="#{livroBean.livro.id}" />
        <f:viewAction action="#{livroBean.carregaPelaId}"
            if="#{param.livroId != null}"></f:viewAction>
    </f:metadata>


    <ui:define name="titulo">
        <p:panelGrid>Novo Livro</p:panelGrid>
    </ui:define>

    <ui:define name="conteudo">
        <h:form>
            <p:messages id="mensagens" />
            <br />
            <p:fieldset legend="Dados do Livro">
                <p:panelGrid columns="2">

                    <p:outputLabel value="Titulo:" for="titulo" />
                    <p:inputText id="titulo" value="#{livroBean.livro.titulo}"
                        required="true" requiredMessage="Título obrigatório!"
                        validatorMessage="Título não pode ser superior a 40 caracteres">
                        <f:validateLength maximum="40" />
                        <f:ajax execute="titulo" render="mensagens" event="blur" />
                    </p:inputText>

                    <p:outputLabel value="ISBN:" for="isbn" />
                    <p:inputMask id="isbn" value="#{livroBean.livro.isbn}"
                        mask="999-9-99-999999-9"
                        validator="#{livroBean.comecaComDigitoUm}">
                        <f:ajax execute="isbn" render="mensagens" event="keypress" />
                    </p:inputMask>

                    <p:outputLabel value="Preço:" for="preco" />
                    <p:inputNumber id="preco" value="#{livroBean.livro.preco}"
                        validatorMessage="Valor deve estar entre R$1.00 e R$1000.00"
                        symbol="R$" symbolPosition="p" decimalSeparator=","
                        thousandSeparator=".">
                        <f:validateDoubleRange minimum="1.00" maximum="1000.00" />
                    </p:inputNumber>

                    <p:outputLabel value="Data de Lançamento:" for="dataLancamento" />
                    <p:calendar id="dataLancamento" pattern="dd/MM/yyyy"
                        value="#{livroBean.livro.dataLancamento.time}">
                        <f:passThroughAttribute name="type" value="date" />
                        <f:passThroughAttribute name="required" value="true" />
                        <f:convertDateTime pattern="dd/MM/yyyy" />
                    </p:calendar>
                </p:panelGrid>
            </p:fieldset>
            <br />
            <p:fieldset legend="Dados do Autor">
                <p:panelGrid columns="4" styleClass="ui-noborder">
                    <p:outputLabel value="Selecione o Autor:" for="autor" />
                    <p:selectOneMenu value="#{livroBean.autorId}" id="autor">
                        <f:selectItems value="#{livroBean.autores}" var="autor"
                            itemLabel="#{autor.nome}" itemValue="#{autor.id}" />
                    </p:selectOneMenu>
                    <p:commandButton value="Gravar Autor" icon="fa fa-plus"
                        action="#{livroBean.gravarAutor}" process="@this autor"
                        update="tabelaAutores">
                    </p:commandButton>

                    <p:commandLink value="Cadastrar novo autor"
                        action="autor?faces-redirect=true" immediate="true" />
                </p:panelGrid>

                <p:dataList id="tabelaAutores" title="Autores do Livro"
                    emptyMessage="Nenhum autor cadastrado para o livro"
                    value="#{livroBean.autoresDoLivro}" var="autor" type="unordered"
                    itemStyleClass="fa fa-arrow-circle-right">

                    <f:facet name="header">Autores do Livro</f:facet>

                    #{autor.nome}
                    <p:commandLink styleClass="fa fa-fw fa-remove"
                        style="text-decoration:none"
                        action="#{livroBean.removerAutorDoLivro(autor)}" process="@this"
                        update="tabelaAutores" />

                </p:dataList>

            </p:fieldset>
            <br />
            <h:commandButton value="Gravar" action="#{livroBean.gravar}">
                <!-- <f:ajax execute="@form" render="@form :formTabelaLivros:tabelaLivros" /> -->
            </h:commandButton>
            <br />
        </h:form>

        <br />

        <h:form id="formTabelaLivros">
            <p:dataTable id="tabelaLivros" value="#{livroBean.livros}"
                var="livro" paginator="true" rows="5">
                <f:facet name="header">Livros</f:facet>

                <p:column headerText="Título" sortBy="#{livro.titulo}"
                    filterBy="#{livro.titulo}" filterMatchMode="startsWith">
                    <p:outputLabel value="#{livro.titulo}" />
                </p:column>

                <p:column headerText="ISBN" sortBy="#{livro.isbn}"
                    filterBy="#{livro.isbn}" filterMatchMode="contains">
                    <p:outputLabel value="#{livro.isbn}" />
                </p:column>

                <p:column headerText="Preço" sortBy="#{livro.preco}"
                    filterBy="#{livro.preco}" filterFunction="livroBean.precoEhMenor">
                    <h:outputText value="#{livro.preco}">
                        <f:convertNumber type="currency" pattern="R$ #0.00"
                            currencySymbol="R$" locale="pt_BR" />
                    </h:outputText>
                </p:column>

                <p:column headerText="Data Lançamento"
                    sortBy="#{livro.dataLancamento.time}"
                    filterBy="#{livro.dataLancamento.time}" filterMatchMode="contains">
                    <p:outputLabel value="#{livro.dataLancamento.time}">
                        <f:convertDateTime pattern="dd/MM/yyyy" />
                    </p:outputLabel>
                </p:column>

                <p:column headerText="Alterar">
                    <h:commandLink value="Alterar"
                        action="#{livroBean.carregar(livro)}" />
                </p:column>

                <p:column headerText="Remover">
                    <h:commandLink value="Remover" action="#{livroBean.remover(livro)}"></h:commandLink>
                </p:column>
            </p:dataTable>
        </h:form>
    </ui:define>

    <ui:define name="textoRodape">
        Cadastro de Livros
    </ui:define>

</ui:composition>
</html>
1 resposta

Olá Bruno,

O erro é de conversão, em algum lugar você está recebendo uma String e tentando pegar um Integer.


Cannot convert livroBean.precoEhMenor of type class java.lang.String to class java.lang.Integer

Em vez de no método

public boolean precoEhMenor(Object valorColuna, Object filtroDigitado, Locale locate)

receber objects troque para os tipos certo que espera.