Error converting a data from one class to another

Asked

Viewed 44 times

1

I’m using JSF in a project, I have a working "W-A" screen that displays the "T-A" table data in a grid. In this grid, each row has a button that forwards to a new screen "W-B" where will be displayed the "detailing" of the previous screen item in a grid, and these items are in table "T-B", which has as foreign key the primary key of table "T-A".

The problem is that when I click on this button I have as return the following error:

AVISO: Cannot convert com.model.Log@5a86506a of type class com.model.Log to class com.model.LogIntegracao
javax.el.ELException: Cannot convert com.model.Log@5a86506a of type class com.model.Log to class com.model.LogIntegracao
    at org.apache.el.lang.ELSupport.coerceToType(ELSupport.java:438)
    at org.apache.el.ExpressionFactoryImpl.coerceToType(ExpressionFactoryImpl.java:46)
    at com.sun.faces.facelets.tag.jsf.core.SetPropertyActionListenerHandler$SetPropertyListener.processAction(SetPropertyActionListenerHandler.java:204)
    at javax.faces.event.ActionEvent.processListener(ActionEvent.java:88)
    at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:778)
    at javax.faces.component.UICommand.broadcast(UICommand.java:300)
    at javax.faces.component.UIData.broadcast(UIData.java:915)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:787)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1252)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:508)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:218)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:962)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:445)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1115)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:662)

My Bean is like this:

package com.model;

import java.io.Serializable;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

import com.DAO.LogDAO;
import com.controller.Conexao;

@ManagedBean(name = "LogMB")
@SessionScoped
public class LogBean implements Serializable {

    private static final long serialVersionUID = 1L;
    private Log log;
    private List<Log> logs;
    private EntradaFiltroLog entradaLog;
    private RetornoFiliais filiais;
    private RetornoIntegracoes integracoes;
    private int[] filiaisSelecionadas;
    private String[] integracoesSelecionadas;
    private LogIntegracao serv;

    public static long getSerialversionuid() {
        return serialVersionUID;
    }

    public Log getLog() {
        return log;
    }

    public void setLog(Log log) {
        this.log = log;
    }

    public List<Log> getLogs() {
        return logs;
    }

    public void setLogs(List<Log> logs) {
        this.logs = logs;
    }

    public EntradaFiltroLog getEntradaLog() {
        return entradaLog;
    }

    public void setEntradaLog(EntradaFiltroLog entradaLog) {
        this.entradaLog = entradaLog;
    }

    public List<Integer> getFiliais() {
        return filiais.getFiliais();
    }

    public void setFiliais(RetornoFiliais filiais) {
        this.filiais = filiais;
    }

    public List<String> getIntegracoes() {
        return integracoes.getIntegracoes();
    }

    public void setIntegracoes(RetornoIntegracoes integracoes) {
        this.integracoes = integracoes;
    }

    public int[] getFiliaisSelecionadas() {
        return filiaisSelecionadas;
    }

    public void setFiliaisSelecionadas(int[] filiaisSelecionadas) {
        this.filiaisSelecionadas = filiaisSelecionadas;
    }

    public String[] getIntegracoesSelecionadas() {
        return integracoesSelecionadas;
    }

    public void setIntegracoesSelecionadas(String[] integracoesSelecionadas) {
        this.integracoesSelecionadas = integracoesSelecionadas;
    }

    public LogIntegracao getServ(Log log) {
        return new LogIntegracao(log);
    }

    public void setServ(LogIntegracao serv) {
        this.serv = serv;
    }

    public void setFiltroFilialIntegracao() throws Exception {
        Connection conn = Conexao.getConnection();
        filiais = LogDAO.buscarFilaisLogs(conn);
        if (!filiais.getFiliais().isEmpty()) {
            integracoes = LogDAO.buscarIntegracoesLogs(conn);
        }
    }

    public LogBean() {
        try {
            setFiltroFilialIntegracao();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        this.log = new Log();
        this.entradaLog = new EntradaFiltroLog();
        logs = setLogs();
    }

    private List<Log> setLogs() {
        Connection conn = null;

        try {
            conn = Conexao.getConnection();
            RetornoLogsExistentes retorno = new RetornoLogsExistentes();
            retorno.setLogs(LogDAO.retornaLogs(conn, entradaLog));
            this.log = new Log();
            setLogs(retorno.getLogs());

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return logs;

    }

    public void BuscarLogs() {
        Connection conn = null;
        logs = new ArrayList<Log>();
        try {
            conn = Conexao.getConnection();
            entradaLog.setFiliais(filiaisSelecionadas);
            entradaLog.setIntegracoes(integracoesSelecionadas);
            RetornoLogsExistentes retorno = new RetornoLogsExistentes();
            retorno.setLogs(LogDAO.retornaLogs(conn, entradaLog));

            setLogs(retorno.getLogs());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public String exibeInconsistencias() {
        return "orq0900a.xhtml";
    }
}

The Log class looks like this:

package com.model;

import java.sql.Date;

public class Log {

    private int id_logint;
    private int filial;
    private int id_integracao;
    private Date dataexecucao;
    private String conteudoenv;
    private String conteudorec;
    private int status;
    private String descrocorr;
    private String integracao;

    public int getId_logint() {
        return id_logint;
    }

    public void setId_logint(int id_logint) {
        this.id_logint = id_logint;
    }

    public int getFilial() {
        return filial;
    }

    public void setFilial(int filial) {
        this.filial = filial;
    }

    public int getId_integracao() {
        return id_integracao;
    }

    public void setId_integracao(int id_integracao) {
        this.id_integracao = id_integracao;
    }

    public Date getData() {
        return dataexecucao;
    }

    public void setData(Date dataexecucao) {
        this.dataexecucao = dataexecucao;
    }

    public String getConteudoenv() {
        return conteudoenv;
    }

    public void setConteudoenv(String conteudoenv) {
        this.conteudoenv = conteudoenv;
    }

    public String getConteudorec() {
        return conteudorec;
    }

    public void setConteudorec(String conteudorec) {
        this.conteudorec = conteudorec;
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public String getDescrocorr() {
        return descrocorr;
    }

    public void setDescrocorr(String descrocorr) {
        this.descrocorr = descrocorr;
    }

    public String getIntegracao() {
        return integracao;
    }

    public void setIntegracao(String integracao) {
        this.integracao = integracao;
    }
}

And the Logintegration class so:

package com.model;

import java.io.Serializable;
import java.sql.Date;

public class LogIntegracao implements Serializable {
    /**
     * 
    */
    private static final long serialVersionUID = 1L;

    private int id_logint;
    private int filial;
    private Date data;
    private int sequencia;
    private String integracao;
    private String chave;
    private String inconsistencia;
    private int status;

    public int getId_logint() {
        return id_logint;
    }

    public void setId_logint(int id_logint) {
        this.id_logint = id_logint;
    }

    public int getFilial() {
        return filial;
    }

    public void setIdFilial(int filial) {
        this.filial = filial;
    }

    public Date getData() {
        return data;
    }

    public void setData(Date data) {
        this.data = data;
    }

    public int getSequencia() {
        return sequencia;
    }

    public void setSequencia(int sequencia) {
        this.sequencia = sequencia;
    }

    public String getIntegracao() {
        return integracao;
    }

    public void setIntegracao(String integracao) {
        this.integracao = integracao;
    }

    public String getChave() {
        return chave;
    }

    public void setChave(String chave) {
        this.chave = chave;
    }

    public String getInconsistencia() {
        return inconsistencia;
    }

    public void setInconsistencia(String inconsistencia) {
        this.inconsistencia = inconsistencia;
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

}

And this is the code of the button on the screen (the #{item} is of the Log type and the #{Logmb.Serv} is of the Logintegracao type):

<p:column headerText="Opções"
    style="width:150px;text-align: center">
    <p:commandButton icon="ui-icon-wrench"
      title="Reprocessar Inconsistencia"
      action="#{LogMB.exibeInconsistencias}">
      <f:setPropertyActionListener value="#{item}"
          target="#{LogMB.serv}" />
    </p:commandButton>
</p:column>

1 answer

2

This can be solved in many ways, but I’m inclined to think about the design and reuse of the Log class.

interface Log {
    /* 
     * Coloque aqui os campos (final static) que tenha em comum 
     * com as classes LogIntegracao e Log
     */

    //Coloque os métodos das que tenha em comum
}

public class LogImp implements Log {
    //Implementação da sua class Log descrita acima
}

public class LogIntegracao implements Serializable, Log {
    //Impelentação da sua class LogIntegracao descrita acima
}

From what I understand of the mistake:

AVISO: Cannot convert com.model.Log@5a86506a of type class com.model.Log to class com.model.LogIntegracao

Classes are not of the same type, causing classes to implement the same interface where, in theory, we could instill the two classes into a common type:

Log logImp = new LogImp();                //instância do LogImp do tipo Log
Log logIntegracao = new LogIntegracao();  //instância do LogIntegracao do tipo Log

Whenever designing classes in java we should worry about the following tip:

If you are adding instances of a user-defined class as elements to an Arraylist, replace your equals() method or your methods contains() or remove() may not behave as expected. [MALA GUPTA, 2015, p. 281]

Note: more details here.

Observing: it is common sense to group the fields of the same type:

private int id_logint;
private int filial;
private int status;
private int id_integracao;
private String conteudoenv;
private String conteudorec;
private String descrocorr;
private String integracao;
private Date dataexecucao;

I hope I’ve helped!


Reference:
[MALA GUPTA, 2015], OCP Java SE 7 Programmer II Certification Guide: PREPARE FOR THE 1ZO-804 EXAM

Browser other questions tagged

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