Após um tempo: Cant instantiate class

Olá, recentemente contratei um plano de VPS para hospedar um sistema que estou fazendo para meus pais…

o servidor tem 2GB de memória ram… e o sistema é bem simples… pra ter uma ideia tem apenas 3 entidades no banco… são 3 CRUD sem quase nenhuma regra…

Não tenho certeza do tempo, acessei no domingo anoite por volta das 22:00 hrs e novamente segunda(hoje) cedo: 07:00.
Depois de um tempo funcionando, ele da o seguinte erro:

[code]An Error Occurred:

Cant instantiate class: br.com.labdiniz.bean.EmpresaBean.

  • Stack Trace

com.sun.faces.mgbean.ManagedBeanCreationException: Cant instantiate class: br.com.labdiniz.bean.EmpresaBean.
at com.sun.faces.mgbean.BeanBuilder.newBeanInstance(BeanBuilder.java:189)
at com.sun.faces.mgbean.BeanBuilder.build(BeanBuilder.java:98)
at com.sun.faces.mgbean.BeanManager.createAndPush(BeanManager.java:405)
at com.sun.faces.mgbean.BeanManager.create(BeanManager.java:265)
at com.sun.faces.el.ManagedBeanELResolver.resolveBean(ManagedBeanELResolver.java:191)
at com.sun.faces.el.ManagedBeanELResolver.getValue(ManagedBeanELResolver.java:73)
at javax.el.CompositeELResolver.getValue(CompositeELResolver.java:67)
at com.sun.faces.el.FacesCompositeELResolver.getValue(FacesCompositeELResolver.java:71)
at org.apache.el.parser.AstIdentifier.getValue(AstIdentifier.java:72)
at org.apache.el.parser.AstValue.getValue(AstValue.java:147)
at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:189)
at com.sun.faces.facelets.el.ELText$ELTextVariable.writeText(ELText.java:220)
at com.sun.faces.facelets.compiler.TextInstruction.write(TextInstruction.java:82)
at com.sun.faces.facelets.compiler.UIInstructions.encodeBegin(UIInstructions.java:78)
at com.sun.faces.facelets.compiler.UILeaf.encodeAll(UILeaf.java:179)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1646)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1646)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1646)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:389)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:127)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:117)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:97)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:135)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:309)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:987)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:579)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:307)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
Caused by: javax.persistence.PersistenceException: org.hibernate.exception.JDBCConnectionException: could not load an entity: [br.com.labdiniz.modelo.Empresa#1]
at org.hibernate.ejb.AbstractEntityManagerImpl.throwPersistenceException(AbstractEntityManagerImpl.java:637)
at org.hibernate.ejb.AbstractEntityManagerImpl.find(AbstractEntityManagerImpl.java:202)
at br.com.labdiniz.banco.DaoGenerico.recuperar(DaoGenerico.java:48)
at br.com.labdiniz.bean.EmpresaBean.(EmpresaBean.java:28)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at java.lang.Class.newInstance0(Class.java:372)
at java.lang.Class.newInstance(Class.java:325)
at com.sun.faces.mgbean.BeanBuilder.newBeanInstance(BeanBuilder.java:184)
… 39 more
Caused by: org.hibernate.exception.JDBCConnectionException: could not load an entity: [br.com.labdiniz.modelo.Empresa#1]
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:74)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.loader.Loader.loadEntity(Loader.java:1874)
at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:48)
at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:42)
at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:3044)
at org.hibernate.event.def.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:395)
at org.hibernate.event.def.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:375)
at org.hibernate.event.def.DefaultLoadEventListener.load(DefaultLoadEventListener.java:139)
at org.hibernate.event.def.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:195)
at org.hibernate.event.def.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:103)
at org.hibernate.impl.SessionImpl.fireLoad(SessionImpl.java:878)
at org.hibernate.impl.SessionImpl.get(SessionImpl.java:815)
at org.hibernate.impl.SessionImpl.get(SessionImpl.java:808)
at org.hibernate.ejb.AbstractEntityManagerImpl.find(AbstractEntityManagerImpl.java:182)
… 48 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed.Connection was implicitly closed by the driver.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:409)
at com.mysql.jdbc.Util.getInstance(Util.java:384)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1015)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:989)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:984)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:929)
at com.mysql.jdbc.ConnectionImpl.throwConnectionClosedException(ConnectionImpl.java:1193)
at com.mysql.jdbc.ConnectionImpl.checkClosed(ConnectionImpl.java:1180)
at com.mysql.jdbc.ConnectionImpl.prepareStatement(ConnectionImpl.java:4137)
at com.mysql.jdbc.ConnectionImpl.prepareStatement(ConnectionImpl.java:4103)
at org.hibernate.jdbc.AbstractBatcher.getPreparedStatement(AbstractBatcher.java:505)
at org.hibernate.jdbc.AbstractBatcher.getPreparedStatement(AbstractBatcher.java:423)
at org.hibernate.jdbc.AbstractBatcher.prepareQueryStatement(AbstractBatcher.java:139)
at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1547)
at org.hibernate.loader.Loader.doQuery(Loader.java:673)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:236)
at org.hibernate.loader.Loader.loadEntity(Loader.java:1860)
… 60 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

The last packet successfully received from the server was 32,251,737 milliseconds ago. The last packet sent successfully to the server was 5 milliseconds ago.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:409)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1118)
at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:3055)
at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:2941)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3489)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1959)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2113)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2568)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2113)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:2275)
at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:186)
at org.hibernate.loader.Loader.getResultSet(Loader.java:1787)
at org.hibernate.loader.Loader.doQuery(Loader.java:674)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:236)
at org.hibernate.loader.Loader.loadEntity(Loader.java:1860)
at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:48)
at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:42)
at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:3044)
at org.hibernate.event.def.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:395)
at org.hibernate.event.def.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:375)
at org.hibernate.event.def.DefaultLoadEventListener.load(DefaultLoadEventListener.java:139)
at org.hibernate.event.def.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:195)
at org.hibernate.event.def.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:103)
at org.hibernate.impl.SessionImpl.fireLoad(SessionImpl.java:878)
at org.hibernate.impl.SessionImpl.get(SessionImpl.java:815)
at org.hibernate.impl.SessionImpl.get(SessionImpl.java:808)
at org.hibernate.ejb.AbstractEntityManagerImpl.find(AbstractEntityManagerImpl.java:182)
at br.com.labdiniz.banco.DaoGenerico.recuperar(DaoGenerico.java:48)
at br.com.labdiniz.bean.EmpresaBean.(EmpresaBean.java:28)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at java.lang.Class.newInstance0(Class.java:372)
at java.lang.Class.newInstance(Class.java:325)
at com.sun.faces.mgbean.BeanBuilder.newBeanInstance(BeanBuilder.java:184)
at com.sun.faces.mgbean.BeanBuilder.build(BeanBuilder.java:98)
at com.sun.faces.mgbean.BeanManager.createAndPush(BeanManager.java:405)
at com.sun.faces.mgbean.BeanManager.create(BeanManager.java:265)
at com.sun.faces.el.ManagedBeanELResolver.resolveBean(ManagedBeanELResolver.java:191)
at com.sun.faces.el.ManagedBeanELResolver.getValue(ManagedBeanELResolver.java:73)
at javax.el.CompositeELResolver.getValue(CompositeELResolver.java:67)
at com.sun.faces.el.FacesCompositeELResolver.getValue(FacesCompositeELResolver.java:71)
at org.apache.el.parser.AstIdentifier.getValue(AstIdentifier.java:72)
at org.apache.el.parser.AstValue.getValue(AstValue.java:147)
at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:189)
at com.sun.faces.facelets.el.ELText$ELTextVariable.writeText(ELText.java:220)
at com.sun.faces.facelets.compiler.TextInstruction.write(TextInstruction.java:82)
at com.sun.faces.facelets.compiler.UIInstructions.encodeBegin(UIInstructions.java:78)
at com.sun.faces.facelets.compiler.UILeaf.encodeAll(UILeaf.java:179)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1646)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1646)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1646)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:389)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:127)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:117)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:97)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:135)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:309)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:987)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:579)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:309)
… 3 more
Caused by: java.io.EOFException: Can not read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpectedly lost.
at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:2502)
at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:2952)
… 72 more[/code]

Respondendo eu mesmo pra ficar mais fácil… vou postar aqui o código da minha EmpresaBean.

EmpresaBean;

@ManagedBean
@SessionScoped
public class EmpresaBean {

    private Empresa empresa;
    private DaoGenerico dao;
    private String anotacao;

    public EmpresaBean() {
        dao = new DaoGenerico();
        if (empresa == null) {
            empresa = new Empresa();
        }
        empresa.setId(1); //o primeiro registro e as configuracoes da empresa, nome, endereco, etc..
        empresa = (Empresa) dao.recuperar(Empresa.class, empresa);
    }
}
//omitido getters and setters

Não sei se precisa mias vou postar meu
DaoGenerico;

public class DaoGenerico {

    private static DaoGenerico daoGenerico = new DaoGenerico();
    private EntityManager em = Persistencia.getInstancia().getEntityManagerFactory().createEntityManager();

    public static DaoGenerico getDaoGenerico() {
        return daoGenerico;
    }

    public EntityManager getEntityManager() {
        return em;
    }

    public DaoGenerico() {
    }

//omitido os metodos de salvar, excluir, etc.. deixei apenas o recuperar...

    public Object recuperar(Class classe, Object objeto) {
        return em.find(classe, Persistencia.getId(objeto));
    }

E aqui vai meu
Persistencia;

public class Persistencia {

    public EntityManagerFactory entityManagerFactory;
    public static Persistencia instancia = new Persistencia();
    public SimpleDateFormat sdf;

    public EntityManagerFactory getEntityManagerFactory() {
        return entityManagerFactory;
    }

    public static Persistencia getInstancia() {
        return instancia;
    }

    public SimpleDateFormat getSdf() {
        return sdf;
    }

    public Persistencia() {
        sdf = new SimpleDateFormat("dd/MM/yyyy");
        entityManagerFactory = Persistence.createEntityManagerFactory("LabDinizPU");
    }

    public static Object getId(Object objeto) {
        Class classe = objeto.getClass();
        for (Field f : getAtributos(classe)) {
            if (f.isAnnotationPresent(Id.class)) {
                try {
                    f.setAccessible(true);
                    return f.get(objeto);
                } catch (Exception e) {
                }

            }
        }

        return null;
    }

    public static String getFieldId(Object objeto) {
        Class classe = objeto.getClass();
        for (Field f : getAtributos(classe)) {
            if (f.isAnnotationPresent(Id.class)) {
                try {
                    f.setAccessible(true);
                    return f.getName();
                } catch (Exception e) {
                }

            }
        }

        return null;
    }

    public static List<Field> getAtributos(Class classe) {
        List<Field> lista = new ArrayList<Field>();
        if (!classe.getSuperclass().equals(Object.class)) {
            lista.addAll(getAtributos(classe.getSuperclass()));
        }
        for (Field f : classe.getDeclaredFields()) {
            if (Modifier.isStatic(f.getModifiers())) {
                continue;
            }
            lista.add(f);
        }
        return lista;
    }
    
    
}

cara, como ta a sua conexao com o banco. nao ta ficando aberta nao? e depois quando vai usar ela expirou.

Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure 

hmmm acho que eh isso mesmo em…

no meu DaoGenerico eu tenho por exemplo o método de salvar assim:

public void Salvar(Object obj){
   em.getTransaction().begin();
   em.persist(obj);
   em.getTransaction().commit();
}

depois do commit eu teria que fechar a conexão? seria isso?

normalmente sim. vc usa algum pool? ou a mantem aberta?

vish… to vendo que preciso estudar mais essa parte de conexão com banco…

a parte de regra, os managed beans, eu vo até bem…

eu tenho apenas as 3 classes;

EmpresaBean (e outros beans… que são quase todos iguais)
DaoGenerico
Persistencia

o dao generico é onde fica os métodos que persiste no banco
que são salvar, recuperar, deletar, etc…

agora sobre a sua pergunta, eu não sei responder…

Eu precisava de uma ajuda nessa parte… olhando meu DaoGenerico após o em.getTransaction().commit(); eu posso dar um close?
em.getTransaction().close();

Esse jeito de programar está errado… olhei no servidor usando o “htop” do linux, e está comendo muita memória para um sistema tão pequeno…

Se alguem puder me indicar um livro bom e atualizado, ou algum tutorial na internet usando
Netbeans 6.8 ou maior (de preferencia o 7 ou 7.1)
jsf 2.0
hibernate

e na parte do banco usando um padrão de projeto correto