[Resolvido] Testar Primeiro EJB , Null Pointer Exception

Opa galera beleza? Estou tendo dificuldades em testar os meus Ejbs…

Tenho um projeto EJB com a sequinte estrutura:

Interface Remota

[code]package ejb3inaction.example;

import javax.ejb.Local;
import javax.ejb.Remote;

@Remote
public interface HelloUser {

public String sayHello(String name);

}[/code]

Bean:

[code]package ejb3inaction.example;

import javax.ejb.Stateless;

@Stateless
public class HelloUserBean implements HelloUser{

public String sayHello(String name) {
	
	return "Hello: " + name + " welcome to EJB3";
	
}

}[/code]

Tenho um projeto Web com um Servlet:

[code]import java.io.IOException;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ejb3inaction.example.HelloUser;
import ejb3inaction.example.HelloUserBean;

public class TestEJB extends HttpServlet {

@EJB
private HelloUser bean;

protected void doGet(HttpServletRequest request, HttpServletResponse response) 
	throws ServletException, IOException {
	
	
	
	response.getWriter().println(bean.sayHello("Gabriel"));
	
	
	
	
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) 
	throws ServletException, IOException {
	
	
	
}

}[/code]

Antes eu subia somente o projeto EJB no Jboss 5.1 e ele não me gerava um JNDI
Agora eu estou usando o Jboss 4.2.2 e aparentemente ele me gera um JNDI pois há um refêrencia do meu bean no GLOBAL JNDI NAMING

No Projeto Web na pasta lib tenho um JAR do meu Projeto EJB(deploy fora do eclipse) e para o eclipse reconhecer o EJB eu adicionei no class path do projeto web o projeto ejb.

Quando eu executo esse código eu recebo uma NullPointerException.

Abaixo o Log do servidor:

13:57:14,774 INFO [Server] Starting JBoss (MX MicroKernel)... 13:57:14,774 INFO [Server] Release ID: JBoss [Trinity] 4.2.2.GA (build: SVNTag=JBoss_4_2_2_GA date=200710221139) 13:57:14,774 INFO [Server] Home Dir: C:\jboss-4.2.2.GA 13:57:14,774 INFO [Server] Home URL: file:/C:/jboss-4.2.2.GA/ 13:57:14,790 INFO [Server] Patch URL: null 13:57:14,790 INFO [Server] Server Name: default 13:57:14,790 INFO [Server] Server Home Dir: C:\jboss-4.2.2.GA\server\default 13:57:14,790 INFO [Server] Server Home URL: file:/C:/jboss-4.2.2.GA/server/default/ 13:57:14,790 INFO [Server] Server Log Dir: C:\jboss-4.2.2.GA\server\default\log 13:57:14,790 INFO [Server] Server Temp Dir: C:\jboss-4.2.2.GA\server\default\tmp 13:57:14,790 INFO [Server] Root Deployment Filename: jboss-service.xml 13:57:15,336 INFO [ServerInfo] Java version: 1.6.0_18,Sun Microsystems Inc. 13:57:15,336 INFO [ServerInfo] Java VM: Java HotSpot(TM) Client VM 16.0-b13,Sun Microsystems Inc. 13:57:15,336 INFO [ServerInfo] OS-System: Windows Vista 6.0,x86 13:57:15,696 INFO [Server] Core system initialized 13:57:17,790 INFO [WebService] Using RMI server codebase: http://localhost:8083/ 13:57:17,790 INFO [Log4jService$URLWatchTimerTask] Configuring from URL: resource:jboss-log4j.xml 13:57:18,259 INFO [TransactionManagerService] JBossTS Transaction Service (JTA version) - JBoss Inc. 13:57:18,259 INFO [TransactionManagerService] Setting up property manager MBean and JMX layer 13:57:18,650 INFO [TransactionManagerService] Starting recovery manager 13:57:18,791 INFO [TransactionManagerService] Recovery manager started 13:57:18,791 INFO [TransactionManagerService] Binding TransactionManager JNDI Reference 13:57:21,340 INFO [EJB3Deployer] Starting java:comp multiplexer 13:57:21,826 INFO [STDOUT] no object for null 13:57:21,841 INFO [STDOUT] no object for null 13:57:21,857 INFO [STDOUT] no object for null 13:57:21,888 INFO [STDOUT] no object for {urn:jboss:bean-deployer}supplyType 13:57:21,904 INFO [STDOUT] no object for {urn:jboss:bean-deployer}dependsType 13:57:24,013 INFO [NativeServerConfig] JBoss Web Services - Native 13:57:24,013 INFO [NativeServerConfig] jbossws-native-2.0.1.SP2 (build=200710210837) 13:57:25,202 INFO [Embedded] Catalina naming disabled 13:57:25,406 INFO [AprLifecycleListener] The Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jre6\bin;.;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;native 13:57:25,484 INFO [Http11Protocol] Initializing Coyote HTTP/1.1 on http-localhost%2F127.0.0.1-8080 13:57:25,484 INFO [AjpProtocol] Initializing Coyote AJP/1.3 on ajp-localhost%2F127.0.0.1-8009 13:57:25,484 INFO [Catalina] Initialization processed in 284 ms 13:57:25,484 INFO [StandardService] Starting service jboss.web 13:57:25,484 INFO [StandardEngine] Starting Servlet Engine: JBossWeb/2.0.1.GA 13:57:25,546 INFO [Catalina] Server startup in 65 ms 13:57:25,703 INFO [TomcatDeployer] deploy, ctxPath=/, warUrl=.../deploy/jboss-web.deployer/ROOT.war/ 13:57:26,640 INFO [TomcatDeployer] deploy, ctxPath=/invoker, warUrl=.../deploy/http-invoker.sar/invoker.war/ 13:57:26,797 INFO [TomcatDeployer] deploy, ctxPath=/jbossws, warUrl=.../deploy/jbossws.sar/jbossws-context.war/ 13:57:26,907 INFO [TomcatDeployer] deploy, ctxPath=/jbossmq-httpil, warUrl=.../deploy/jms/jbossmq-httpil.sar/jbossmq-httpil.war/ 13:57:27,579 INFO [TomcatDeployer] deploy, ctxPath=/web-console, warUrl=.../deploy/management/console-mgr.sar/web-console.war/ 13:57:28,219 INFO [MailService] Mail Service bound to java:/Mail 13:57:28,455 INFO [RARDeployment] Required license terms exist, view META-INF/ra.xml in .../deploy/jboss-ha-local-jdbc.rar 13:57:28,533 INFO [RARDeployment] Required license terms exist, view META-INF/ra.xml in .../deploy/jboss-ha-xa-jdbc.rar 13:57:28,548 INFO [RARDeployment] Required license terms exist, view META-INF/ra.xml in .../deploy/jboss-local-jdbc.rar 13:57:28,689 INFO [RARDeployment] Required license terms exist, view META-INF/ra.xml in .../deploy/jboss-xa-jdbc.rar 13:57:28,736 INFO [RARDeployment] Required license terms exist, view META-INF/ra.xml in .../deploy/jms/jms-ra.rar 13:57:28,783 INFO [RARDeployment] Required license terms exist, view META-INF/ra.xml in .../deploy/mail-ra.rar 13:57:28,814 INFO [RARDeployment] Required license terms exist, view META-INF/ra.xml in .../deploy/quartz-ra.rar 13:57:28,830 INFO [QuartzResourceAdapter] start quartz!!! 13:57:28,923 INFO [SimpleThreadPool] Job execution threads will use class loader of thread: main 13:57:28,955 INFO [QuartzScheduler] Quartz Scheduler v.1.5.2 created. 13:57:28,955 INFO [RAMJobStore] RAMJobStore initialized. 13:57:28,955 INFO [StdSchedulerFactory] Quartz scheduler 'DefaultQuartzScheduler' initialized from default resource file in Quartz package: 'quartz.properties' 13:57:28,955 INFO [StdSchedulerFactory] Quartz scheduler version: 1.5.2 13:57:28,955 INFO [QuartzScheduler] Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED started. 13:57:30,314 INFO [ConnectionFactoryBindingService] Bound ConnectionManager 'jboss.jca:service=DataSourceBinding,name=DefaultDS' to JNDI name 'java:DefaultDS' 13:57:30,612 INFO [A] Bound to JNDI name: queue/A 13:57:30,612 INFO [B] Bound to JNDI name: queue/B 13:57:30,612 INFO [C] Bound to JNDI name: queue/C 13:57:30,612 INFO [D] Bound to JNDI name: queue/D 13:57:30,612 INFO [ex] Bound to JNDI name: queue/ex 13:57:30,643 INFO [testTopic] Bound to JNDI name: topic/testTopic 13:57:30,643 INFO [securedTopic] Bound to JNDI name: topic/securedTopic 13:57:30,643 INFO [testDurableTopic] Bound to JNDI name: topic/testDurableTopic 13:57:30,643 INFO [testQueue] Bound to JNDI name: queue/testQueue 13:57:30,690 INFO [UILServerILService] JBossMQ UIL service available at : localhost/127.0.0.1:8093 13:57:30,737 INFO [DLQ] Bound to JNDI name: queue/DLQ 13:57:30,878 INFO [ConnectionFactoryBindingService] Bound ConnectionManager 'jboss.jca:service=ConnectionFactoryBinding,name=JmsXA' to JNDI name 'java:JmsXA' 13:57:30,909 INFO [TomcatDeployer] deploy, ctxPath=/jmx-console, warUrl=.../deploy/jmx-console.war/ 13:57:31,112 INFO [Http11Protocol] Starting Coyote HTTP/1.1 on http-localhost%2F127.0.0.1-8080 13:57:31,128 INFO [AjpProtocol] Starting Coyote AJP/1.3 on ajp-localhost%2F127.0.0.1-8009 13:57:31,143 INFO [Server] JBoss (MX MicroKernel) [4.2.2.GA (build: SVNTag=JBoss_4_2_2_GA date=200710221139)] Started in 16s:353ms 13:57:36,299 INFO [JmxKernelAbstraction] creating wrapper delegate for: org.jboss.ejb3.stateless.StatelessContainer 13:57:36,299 INFO [JmxKernelAbstraction] installing MBean: jboss.j2ee:jar=EJBinAction.jar,name=HelloUserBean,service=EJB3 with dependencies: 13:57:36,535 INFO [EJBContainer] STARTED EJB: ejb3inaction.example.HelloUserBean ejbName: HelloUserBean 13:57:36,597 INFO [EJB3Deployer] Deployed: file:/C:/Users/Gabriel Castilho/workspace/.metadata/.plugins/org.jboss.ide.eclipse.as.core/JBoss_4.2_Runtime_Server/deploy/EJBinAction.jar/ 13:57:36,628 INFO [TomcatDeployer] deploy, ctxPath=/EJBinActionTeste, warUrl=file:/C:/Users/Gabriel Castilho/workspace/.metadata/.plugins/org.jboss.ide.eclipse.as.core/JBoss_4.2_Runtime_Server/deploy/EJBinActionTeste.war/

Preciso muito de ajuda estou com essa duvida já a bastante tempo e não vejo solução.

Abraço galera e obrigado.

Poste seu web.xml

breno, não fiz nenhuma alteração no web.xml
segue ele,


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>EJBinActionTeste</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
  <servlet>
    <servlet-name>TestEJB</servlet-name>
    <servlet-class>TestEJB</servlet-class>
  </servlet>
  
  <servlet-mapping>
    <servlet-name>TestEJB</servlet-name>
    <url-pattern>/TestEJB</url-pattern>
  </servlet-mapping>
</web-app>

abraço.

EDIT:

O Erro esqueci de postar:

java.lang.NullPointerException at TestEJB.doGet(TestEJB.java:24) at javax.servlet.http.HttpServlet.service(HttpServlet.java:690) at javax.servlet.http.HttpServlet.service(HttpServlet.java:803) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175) at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:182) at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:84) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:157) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:262) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:446) at java.lang.Thread.run(Unknown Source)

Então Gabriel, para utilizar o @EJB dentro de um servlet vc precisa colocar umas declarações a mais no web.xml para o container injetar o ejb para vc…
Nunca fiz dessa forma(não gosto muito de configurar xml) pois prefiro utilizar o lookup…
As tags são as seguintes:

    
    <!-- Remoto  -->
    <ejb-ref>
       <ejb-ref-name></ejb-ref-name>
       <ejb-ref-type></ejb-ref-type> 
       <remote></remote>
    </ejb-ref>
    
     <!-- Local -->
     <ejb-local-ref>
        <ejb-ref-name></ejb-ref-name>
        <ejb-ref-type></ejb-ref-type> 
        <local></local>
     </ejb-local-ref>

Vai testando ai cara…
Abraços…

Abraço…

A série 4.x do JBoss não é inteiramente compatível com a especificação JavaEE 5, embora suporte o uso de EJB3. Uma das incompatibilidades é injeção via @EJB fora do container EJB, como em uma servlet, isso de fato não funciona.

A versão 5.x é 100% certificada JavaEE5 portanto injeção de EJBs em Servlets funcionam sem problemas.

Portanto pra fazer o que vc quer, utilize as versões da série 5 do JBoss, e não a versão 4.

breno vou testar aqui mano! Obrigado!!

Alessandro no Jboss 5.1 não sobe meu EJB
no Jboss 6.0 eu não consigo configurar ele no eclipse. =/

Vou fazer uns testes aqui. Abraço se alguem puder dar mais alguma ajuda agradeço.

Abraço galera obrigado.

Aonde é que eu vejo o JNDI?

Não estou achando qual o nome que está nele:

No Log:

No Global JNDI Namespace:

Global JNDI Namespace
  +- TopicConnectionFactory (class: org.jboss.naming.LinkRefPair)
  +- jmx (class: org.jnp.interfaces.NamingContext)
  |   +- invoker (class: org.jnp.interfaces.NamingContext)
  |   |   +- RMIAdaptor (proxy: $Proxy47 implements interface org.jboss.jmx.adaptor.rmi.RMIAdaptor,interface org.jboss.jmx.adaptor.rmi.RMIAdaptorExt)
  |   +- rmi (class: org.jnp.interfaces.NamingContext)
  |   |   +- RMIAdaptor[link -> jmx/invoker/RMIAdaptor] (class: javax.naming.LinkRef)
  +- HTTPXAConnectionFactory (class: org.jboss.mq.SpyXAConnectionFactory)
  +- ConnectionFactory (class: org.jboss.mq.SpyConnectionFactory)
  +- UserTransactionSessionFactory (proxy: $Proxy15 implements interface org.jboss.tm.usertx.interfaces.UserTransactionSessionFactory)
  +- HTTPConnectionFactory (class: org.jboss.mq.SpyConnectionFactory)
  +- XAConnectionFactory (class: org.jboss.mq.SpyXAConnectionFactory)
  +- TransactionSynchronizationRegistry (class: com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionSynchronizationRegistryImple)
  +- UserTransaction (class: org.jboss.tm.usertx.client.ClientUserTransaction)
  +- HelloUserBean (class: org.jnp.interfaces.NamingContext)
  |   +- remote (proxy: $Proxy64 implements interface ejb3inaction.example.HelloUser,interface org.jboss.ejb3.JBossProxy)
  +- UILXAConnectionFactory[link -> XAConnectionFactory] (class: javax.naming.LinkRef)
  +- UIL2XAConnectionFactory[link -> XAConnectionFactory] (class: javax.naming.LinkRef)
  +- queue (class: org.jnp.interfaces.NamingContext)
  |   +- A (class: org.jboss.mq.SpyQueue)
  |   +- testQueue (class: org.jboss.mq.SpyQueue)
  |   +- ex (class: org.jboss.mq.SpyQueue)
  |   +- DLQ (class: org.jboss.mq.SpyQueue)
  |   +- D (class: org.jboss.mq.SpyQueue)
  |   +- C (class: org.jboss.mq.SpyQueue)
  |   +- B (class: org.jboss.mq.SpyQueue)
  +- topic (class: org.jnp.interfaces.NamingContext)
  |   +- testDurableTopic (class: org.jboss.mq.SpyTopic)
  |   +- testTopic (class: org.jboss.mq.SpyTopic)
  |   +- securedTopic (class: org.jboss.mq.SpyTopic)
  +- console (class: org.jnp.interfaces.NamingContext)
  |   +- PluginManager (proxy: $Proxy48 implements interface org.jboss.console.manager.PluginManagerMBean)
  +- UIL2ConnectionFactory[link -> ConnectionFactory] (class: javax.naming.LinkRef)
  +- HiLoKeyGeneratorFactory (class: org.jboss.ejb.plugins.keygenerator.hilo.HiLoKeyGeneratorFactory)
  +- UILConnectionFactory[link -> ConnectionFactory] (class: javax.naming.LinkRef)
  +- QueueConnectionFactory (class: org.jboss.naming.LinkRefPair)
  +- UUIDKeyGeneratorFactory (class: org.jboss.ejb.plugins.keygenerator.uuid.UUIDKeyGeneratorFactory)

O JNDI é o nome do meu Bean? (linha 15)

É a linha 15 + 16:

# +- HelloUserBean (class: org.jnp.interfaces.NamingContext)  
#   |   +- remote (proxy: $Proxy64 implements interface ejb3inaction.example.HelloUser,interface org.jboss.ejb3.JBossProxy)  

… ou seja, seu ejb esta em “HelloUserBean/remote”

Utilize o JBoss na versão 5.1.

Ae funcionou usando o LOOKUP ao invés do @EJB e colocando o JNDI no lookup.

Aeeeeeeeee =D

Muito obrigado pessoal!!

breno e lazarotti

Abraço!!

Se alguem tiver o mesmo erro , ai o código





import java.io.IOException;
import java.util.Properties;

import javax.ejb.EJB;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ejb3inaction.example.HelloUser;
import ejb3inaction.example.HelloUserBean;

public class TestEJB extends HttpServlet {

	
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
		throws ServletException, IOException {
		
		InitialContext ic;
		HelloUser hellouser = null;
		
		try {
			Properties prop = new Properties();   
		      prop.put("java.naming.factory.initial","org.jnp.interfaces.NamingContextFactory");   
		      prop.put(InitialContext.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");   
		      prop.put(InitialContext.PROVIDER_URL,"jnp://localhost:1099");   
		     

			ic = new InitialContext(prop);
			hellouser = (HelloUser) ic.lookup("HelloUserBean/local");
		} catch (NamingException e) {
			e.printStackTrace();
		}
		
		response.getWriter().println(hellouser.sayHello("Gabriel"));		
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
		throws ServletException, IOException {
		
		
		
	}

}


Legal que funcionou Gabriel, mas vá com calma.
Se vc utiliza a tecnologia JavaEE 5 o interessante é tirar proveito de seus recursos, como Dependency Injection. Embora lookup funcione, o mais indicado hoje, seja por produtividade, clareza no código e testabilidade, é usar DI.

Não desista, reveja seu código e vá atrás do erro. Se você esta tentando aprender a tecnologia, não utilize atalhos.

PS:Se vc quer utilizar o EJB como local, como você fez no lookup, anote a interface do EJB como local, não como remote (embora o JBoss otimize interfaces remotas que são invocadas localmente, as tratando como local).

Alessandro estou agora seguindo a aplicação do livro e utilizando DI só não pude testar ainda, no meu exemplo não funcionou realmente, vou ver agora no exemplo da aplicação do livro e ver se funciona.

PS: No livro o que dá a entender é que o servlet e o ejb sobe no mesmo projeto.

EDIT…

O que eu fiquei mesmo sem entender foi o porque de não funcionar com @EJB se ele faz o mesmo trabalho ao meu ver
vou testar passando um atributo nome para o @Stateless e ver se ele encontra.

Amanha eu testo e posto.

Obrigado pela atenção mano!
Abraço

[quote=GabrielCardelli]Se alguem tiver o mesmo erro , ai o código

[code]

import java.io.IOException;
import java.util.Properties;

import javax.ejb.EJB;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ejb3inaction.example.HelloUser;
import ejb3inaction.example.HelloUserBean;

public class TestEJB extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response) 
	throws ServletException, IOException {
	
	InitialContext ic;
	HelloUser hellouser = null;
	
	try {
		Properties prop = new Properties();   
	      prop.put("java.naming.factory.initial","org.jnp.interfaces.NamingContextFactory");   
	      prop.put(InitialContext.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");   
	      prop.put(InitialContext.PROVIDER_URL,"jnp://localhost:1099");   
	     

		ic = new InitialContext(prop);
		hellouser = (HelloUser) ic.lookup("HelloUserBean/local");
	} catch (NamingException e) {
		e.printStackTrace();
	}
	
	response.getWriter().println(hellouser.sayHello("Gabriel"));		
	
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) 
	throws ServletException, IOException {
	
	
	
}

}

[/code][/quote]

Valeu amigo!! por esse seu post ai, conseguir aprender como funciona o EJB 3, de inicio…
Agora, tenho um livro EJB3 in Action pela frente para ler =]

Valeu mesmo

:shock: :lol: :wink: