GUJ Discussões   :   últimos tópicos   |   categorias   |   GUJ Respostas

[RESOLVIDO] java.lang.NoClassDefFoundError: Could not initialize class financeiro.util.JpaUtil

Preciso de ajuda com a exibição de uma página de resultados de consulta de lançamentos do tutorial do ebook da Algaworks. Qualquer ajuda será bem vinda!

Segue o exibido no console:

jul 25, 2016 9:02:14 PM com.sun.faces.lifecycle.InvokeApplicationPhase execute
ADVERTÊNCIA: #{consultaLancamentosBean.consultar}: java.lang.NoClassDefFoundError: Could not initialize class com.janaina.financeiro.util.JpaUtil
javax.faces.FacesException: #{consultaLancamentosBean.consultar}: java.lang.NoClassDefFoundError: Could not initialize class com.janaina.financeiro.util.JpaUtil
	at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118)
	at javax.faces.component.UIViewAction.broadcast(UIViewAction.java:559)
	at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
	at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
	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:198)
	at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
	at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
	at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
	at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1096)
	at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:674)
	at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
	at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
	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.faces.el.EvaluationException: java.lang.NoClassDefFoundError: Could not initialize class com.janaina.financeiro.util.JpaUtil
	at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
	at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
	... 28 more
Caused by: java.lang.NoClassDefFoundError: Could not initialize class com.janaina.financeiro.util.JpaUtil
	at com.janaina.financeiro.controller.ConsultaLancamentosBean.consultar(ConsultaLancamentosBean.java:21)
	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 org.apache.el.parser.AstValue.invoke(AstValue.java:247)
	at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:267)
	at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
	at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
	... 29 more

jul 25, 2016 9:02:14 PM com.sun.faces.context.ExceptionHandlerImpl log
1100: JSF1073: javax.faces.FacesException obtido durante o processamento de INVOKE_APPLICATION 5: UIComponent-ClientId=, Message=#{consultaLancamentosBean.consultar}: java.lang.NoClassDefFoundError: Could not initialize class com.janaina.financeiro.util.JpaUtil
jul 25, 2016 9:02:14 PM com.sun.faces.context.ExceptionHandlerImpl log
1100: #{consultaLancamentosBean.consultar}: java.lang.NoClassDefFoundError: Could not initialize class com.janaina.financeiro.util.JpaUtil
javax.faces.FacesException: #{consultaLancamentosBean.consultar}: java.lang.NoClassDefFoundError: Could not initialize class com.janaina.financeiro.util.JpaUtil
	at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:89)
	at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
	at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
	at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
	at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
	at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
	at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1096)
	at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:674)
	at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
	at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
	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.faces.FacesException: #{consultaLancamentosBean.consultar}: java.lang.NoClassDefFoundError: Could not initialize class com.janaina.financeiro.util.JpaUtil
	at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118)
	at javax.faces.component.UIViewAction.broadcast(UIViewAction.java:559)
	at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
	at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
	at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
	... 24 more
Caused by: javax.faces.el.EvaluationException: java.lang.NoClassDefFoundError: Could not initialize class com.janaina.financeiro.util.JpaUtil
	at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
	at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
	... 28 more
Caused by: java.lang.NoClassDefFoundError: Could not initialize class com.janaina.financeiro.util.JpaUtil
	at com.janaina.financeiro.controller.ConsultaLancamentosBean.consultar(ConsultaLancamentosBean.java:21)
	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 org.apache.el.parser.AstValue.invoke(AstValue.java:247)
	at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:267)
	at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
	at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
	... 29 more

—> ConsultaLancamentos.xml:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:f="http://xmlns.jcp.org/jsf/core"
	xmlns:h="http://xmlns.jcp.org/jsf/html">
<h:head>
	<title>Consulta de lançamentos</title>
</h:head>
<h:body>
	<f:metadata>
		<f:viewAction action="#{consultaLancamentosBean.consultar}" />
	</f:metadata>
	<h1>Consulta de lançamentos</h1>
	<h:form id="frm">
		<h:dataTable value="#{consultaLancamentosBean.lancamentos}"
			var="lancamento" border="1" cellspacing="0" cellpadding="2">
			<h:column>
				<f:facet name="header">
					<h:outputText value="Pessoa" />
				</f:facet>
				<h:outputText value="#{lancamento.pessoa.nome}" />
			</h:column>
			<h:column>
				<f:facet name="header">
					<h:outputText value="Descrição" />
				</f:facet>
				<h:outputText value="#{lancamento.descricao}" />
			</h:column>
			<h:column>
				<f:facet name="header">
					<h:outputText value="Tipo" />
				</f:facet>
				<h:outputText value="#{lancamento.tipo}" />
			</h:column>
			<h:column>
				<f:facet name="header">
					<h:outputText value="Valor" />
				</f:facet>
				<h:outputText value="#{lancamento.valor}" />
			</h:column>
			<h:column>
				<f:facet name="header">
					<h:outputText value="Data de vencimento" />
				</f:facet>
				<h:outputText value="#{lancamento.dataVencimento}" />
			</h:column>
			<h:column>
				<f:facet name="header">
					<h:outputText value="Data de pagamento" />
				</f:facet>
				<h:outputText value="#{lancamento.dataPagamento}" />
			</h:column>
		</h:dataTable>
	</h:form>
</h:body>
</html>

—> ConsultaLancamentosBean.java:

package com.janaina.financeiro.controller;

import java.io.Serializable;
import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.view.ViewScoped;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;

import com.janaina.financeiro.model.Lancamento;
import com.janaina.financeiro.util.JpaUtil;

@ManagedBean
@ViewScoped
public class ConsultaLancamentosBean implements Serializable {
	private static final long serialVersionUID = 1L;
	private List<Lancamento> lancamentos;

	public void consultar() {
		EntityManager manager = JpaUtil.getEntityManager();
		TypedQuery<Lancamento> query = manager.createQuery("from Lancamento", Lancamento.class);
		this.lancamentos = query.getResultList();
		manager.close();
	}

	public List<Lancamento> getLancamentos() {
		return lancamentos;
	}
}

----> JpaUtil.java:

package com.janaina.financeiro.util;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

//JpaUtil armazena a instância compartilhada de EntityManagerFactory em uma variável estática
//Qualquer código terá acesso fácil e rápido
//Sempre que for preciso uma EntityManager basta chamar:
//EntityManager manager = JpaUtil.getEntityManager();

public class JpaUtil {
	private static EntityManagerFactory factory;
	static {
		factory = Persistence.createEntityManagerFactory("FinanceiroPU");
	}

	public static EntityManager getEntityManager() {
		return factory.createEntityManager();
	}
}

veja se o persistence unit está com esse nome realmente (FinanceiroPU), talvez tenha digitado errado.
Confere e dá um retorno.

1 Curtida

Tá com esse nome sim…Aqui vai o persistence.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
	version="2.1">

<persistence-unit name="FinanceiroPU">
	<provider>org.hibernate.ejb.HibernatePersistence</provider>
	<class>com.janaina.financeiro.model.Pessoa</class>
	<class>com.janaina.financeiro.model.Lancamento</class>

	<properties>
		<property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost:5432/financeiro" />
		<property name="javax.persistence.jdbc.user" value="postgres" />
		<property name="javax.persistence.jdbc.password" value="postgres" />
		<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver" />

		<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect" />
		<property name="hibernate.show_sql" value="true" />
		<property name="hibernate.format_sql" value="true" />
		<property name="hibernate.hbm2ddl.auto" value="update" />
	</properties>
</persistence-unit>

Certo, vamos por eliminatória… onde está o seu arquivo persistence.xml?
Ele deve estar dentro de /src/main/resources/META-INF

1 Curtida

Certo, veja que no seu projeto tem uma notificação de erro, pra saber qual é, faça o seguinte:
perto da aba ‘servers’ tem uma aba chamada ‘markers’, manda um print dela.

1 Curtida

Faça o seguinte, vá para a pasta do seu projeto e lá dentro terá uma pasta chamada .settings que terá o arquivo ‘org.eclipse.wst.common.project.facet.core’, abra com um editor de texto e substitua essa tag:

<installed facet="jst.web" version="2.5"/>

Provavelmente no seu web.xml a versão deve estar diferente do arquivo que citei acima.
Só pra garantir, dá um update no maven.
Suba o projeto novamente, e manda o log do servidor caso dê erro.

1 Curtida

Em ‘org.eclipse.wst.common.project.facet.core’ substituí a tag
<installed facet="jst.web" version="3.1"/> pela tag que você me passou:
<installed facet="jst.web" version="2.5"/> e na aba Makers do projeto o erro sumiu.

Quando executo o ConsultaLancamentos.xhtml dá o erro 404 e não aparece nada no Console:

Certo. Como está o seu web xml?
veja se na tag servlet-mapping está assim:

    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>/faces/*.xhtml</url-pattern>
    </servlet-mapping>

e veja também se o ConsultaLancamentos.xhtml está dentro de src/main/webapp/

1 Curtida

Consegui resolver o problema! Mas respondendo a sua pergunta @Alandamatta, a minha tag sevlet-mapping está assim (web.xml):

   <context-param>
		<param-name>javax.faces.PROJECT_STAGE</param-name>
		<param-value>Development</param-value>
	</context-param>

	<servlet>
		<servlet-name>Faces Servlet</servlet-name>
		<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>Faces Servlet</servlet-name>
		<url-pattern>/faces/*</url-pattern>
	</servlet-mapping>

E o ConsultaLancamentos.xhtml está dentro de src/main/webapp/

O persistence.xml está assim:

<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
	version="2.1">

	<persistence-unit name="FinanceiroPU">
		<provider>org.hibernate.ejb.HibernatePersistence</provider>
		<class>com.janaina.financeiro.model.Lancamento</class>
		<class>com.janaina.financeiro.model.Pessoa</class>

		<properties>
			<property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost:5432/financeiro" />
			<property name="javax.persistence.jdbc.user" value="postgres" />
			<property name="javax.persistence.jdbc.password" value="postgres" />
			<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver" />

			<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect" />
			<property name="hibernate.show_sql" value="true" />
			<property name="hibernate.format_sql" value="true" />
			<property name="hibernate.hbm2ddl.auto" value="update" />
		</properties>
	</persistence-unit>
</persistence>

Bom…percebi que as causas do meu problema foram:

  1. Estava usando Java JRE ao invé de JDK no projeto. Pra corrigir isso fiz o seguinte:
    Rigth-click no projeto > Properties > Java Build Path > Libraries > Selecionei o JRE que estava usando > Edit > Installed JREs > Search > Caminho JDK (C:\Program Files\Java\jdk1.8.0_101).

  2. Depois percebi que não estava conseguindo conectar o postgreesql. Então desinstalei o Postgreesql e também tive que apagar o diretório que ficou em Arquivos de Programas após a desinstalação. Depois reinstalei!

  3. Por último:
    Rigth-click no projeto > Run as > Maven > Maven Clean e depois
    Rigth-click no projeto > Run as > Maven >Maven install

Os passos acima funcionaram pra mim…Espero que ajude outras pessoas!

Que bom que conseguiu resolver =) eu iria demorar para descobrir q era esse o problema xD, apesar de ser simples!
Bons estudos!

1 Curtida

Sua ajuda foi essencial! Muito obrigada :slight_smile:

guj1

Estava enfrentando este mesmo problema e para mim funcionou colocando o arquivo persistence.xml dentro do source folder: /src/main/resources/META-INF, obrigado!