Get exception when using injection with a simple HelloEJB project - ejb

I am now learning EJB and got a problem when testing the Injection functionality. Here is my code (I create an EJB project in Eclipse).
I run the EJB with embedded Glassfish, and run the test(main) independently, but always get this exception:
java.lang.NullPointerException
at com.example.MainUsingInjection.runTest(MainUsingInjection.java:11)
at com.example.MainUsingInjection.main(MainUsingInjection.java:20)
I hope anyone can help me with this. Thank you very much.
HelloSessionBean.java
package com.example;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
#Stateless
#LocalBean
public class HelloSessionBean implements HelloSessionBeanRemote {
public HelloSessionBean() { }
public void helloMethod() {
System.out.println("Hello World!\n");
}
}
HelloSessionBeanRemote.java
package com.example;
import javax.ejb.Remote;
#Remote
public interface HelloSessionBeanRemote {
public void helloMethod();
}
MainUsingJnjection.java
package com.example;
import javax.ejb.EJB;
public class MainUsingInjection {
#EJB(name="HelloSessionBean")
public static HelloSessionBeanRemote bean;
public void runTest() throws Exception {
bean.helloMethod();
}
public static void main(String[] args) {
MainUsingInjection cli = new MainUsingInjection();
try {
cli.runTest();
} catch (Exception e) {
e.printStackTrace();
}
}
}

The stack trace suggests that you've directly launched the main method. In order to use injection in the main class, you must use the application client container.

Related

Exception in thread "main" java.lang.IllegalStateException: EJBCLIENT000025: No EJB receiver available

I created an EJB project and another project to test the first.
This screenshot gives an overview about my two projects.
The class main on the test project is:
public class TestEjb
{
public static void main(String[] args)
{
GestionEmployeeRemote gestion = null;
try {
Properties jndiProperties = new Properties();
jndiProperties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
Context context = new InitialContext(jndiProperties);
Object o = context.lookup("ejb:/FirstEJBProject/GestionEmployee!services.GestionEmployeeRemote");
gestion = (GestionEmployeeRemote) o;
} catch (NamingException e) {
e.printStackTrace();
}
createEmployee(gestion);
}
public static void createEmployee(GestionEmployeeRemote gestion)
{
Employee employee = new Employee("Foulen", "Ben Foulen", new Date(), "Directeur");
gestion.createEmployee(employee);
}
The file jndi.properties is:
java.naming.factory.url.pkgs=org.jboss.ejb.client.naming
java.naming.factory.initial=org.jboss.naming.remote.client.InitialContextFactory
java.naming.provider.url=remote://localhost:4447
jboss.naming.client.ejb.context=true
jboss.naming.client.connect.options.org.xnio.Options.SASL_POLICY_NOPLAINTEXT=false
The class GestionEmployee.java is:
package services;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import persistance.Employee;
/**
* Session Bean implementation class GestionEmployee
*/
#Stateless
public class GestionEmployee implements GestionEmployeeRemote, GestionEmployeeLocal {
#PersistenceContext
EntityManager em;
public GestionEmployee() {
// TODO Auto-generated constructor stub
}
#Override
public void createEmployee(Employee employee) {
em.persist(employee);
}
#Override
public void updateEmployee(Employee employee) {
em.merge(employee);
}
#Override
public void deleteEmployee(Employee employee) {
em.remove(employee);
}
#Override
public Employee getEmployeeById(int idEmployee) {
Employee elmployee = em.find(Employee.class, idEmployee);
return null;
}
#Override
public List<Employee> getAllEmployee() {
Query query = em.createQuery("select e from Employee e");
return query.getResultList();
}
}
The class GestionEmployeeRemote.java is:
package services;
import java.util.List;
import javax.ejb.Remote;
import persistance.Employee;
#Remote
public interface GestionEmployeeRemote
{
public void createEmployee (Employee employee);
public void updateEmployee (Employee employee);
public void deleteEmployee (Employee employee);
public Employee getEmployeeById (int idEmployee);
public List<Employee> getAllEmployee();
}
After running the class main, I got this error:
Exception in thread "main" java.lang.IllegalStateException: EJBCLIENT000025: No EJB receiver available for handling [appName:, moduleName:FirstEJBProject, distinctName:] combination for invocation context org.jboss.ejb.client.EJBClientInvocationContext#a47962
at org.jboss.ejb.client.EJBClientContext.requireEJBReceiver(EJBClientContext.java:749)
at org.jboss.ejb.client.ReceiverInterceptor.handleInvocation(ReceiverInterceptor.java:116)
at org.jboss.ejb.client.EJBClientInvocationContext.sendRequest(EJBClientInvocationContext.java:183)
at org.jboss.ejb.client.EJBInvocationHandler.sendRequestWithPossibleRetries(EJBInvocationHandler.java:253)
at org.jboss.ejb.client.EJBInvocationHandler.doInvoke(EJBInvocationHandler.java:198)
at org.jboss.ejb.client.EJBInvocationHandler.doInvoke(EJBInvocationHandler.java:181)
at org.jboss.ejb.client.EJBInvocationHandler.invoke(EJBInvocationHandler.java:144)
at com.sun.proxy.$Proxy0.createEmployee(Unknown Source)
at test.TestEjb.createEmployee(TestEjb.java:37)
at test.TestEjb.main(TestEjb.java:31)
I'm looking for finding a solution for this issue, any help is appreciated.Thanks a lot.

Simple example for 'ScheduledService' in Javafx

I am a student and learning JavaFX since a month.
I am developing a application where I want a service to repeatedly start again after its execution of the task. For this I have come to know that 'ScheduledService' is used.
So can anybody please explain the use of scheduledservice with simple example and also how it differs from the 'Service' in JavaFX. Thanks ;)
EDIT : How can I define that this ScheduledService named DataThread should be restarted every 5 seconds ?
public class DataThread extends ScheduledService<Void>
{
#Override
public Task<Void> createTask() {
return new Task<Void>() {
#Override
public Void call() throws Exception {
for(i=0;i<10;i++)
{
System.out.println(""+i);
}
return null;
}
};
}
}
Considering you have a sound knowledge of Service class. ScheduledService is just a Service with a Scheduling functionality.
From the docs
The ScheduledService is a Service which will automatically restart itself after a successful execution, and under some conditions will restart even in case of failure
So we can say it as,
Service -> Execute One Task
ScheduledService -> Execute Same Task at regular intervals
A very simple example of Scheduled Service is the TimerService, which counts the number of times the Service Task has been called. It is scheduled to call it every 1 second
import java.util.concurrent.atomic.AtomicInteger;
import javafx.application.Application;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.concurrent.ScheduledService;
import javafx.concurrent.Task;
import javafx.concurrent.WorkerStateEvent;
import javafx.event.EventHandler;
import javafx.stage.Stage;
import javafx.util.Duration;
public class TimerServiceApp extends Application {
#Override
public void start(Stage stage) throws Exception {
TimerService service = new TimerService();
AtomicInteger count = new AtomicInteger(0);
service.setCount(count.get());
service.setPeriod(Duration.seconds(1));
service.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
#Override
public void handle(WorkerStateEvent t) {
System.out.println("Called : " + t.getSource().getValue()
+ " time(s)");
count.set((int) t.getSource().getValue());
}
});
service.start();
}
public static void main(String[] args) {
launch();
}
private static class TimerService extends ScheduledService<Integer> {
private IntegerProperty count = new SimpleIntegerProperty();
public final void setCount(Integer value) {
count.set(value);
}
public final Integer getCount() {
return count.get();
}
public final IntegerProperty countProperty() {
return count;
}
protected Task<Integer> createTask() {
return new Task<Integer>() {
protected Integer call() {
//Adds 1 to the count
count.set(getCount() + 1);
return getCount();
}
};
}
}
}

Not able to call ejb on same machine using client class

I am new to EJB. I tried an example from java_for_web_with_servlets_jsp_and_ejb book. The following code creates an session been called Adder which adds two integers:
Adder.java:
package com.brainysoftware.ejb;
import java.rmi.RemoteException;
import javax.ejb.EJBObject;
public interface Adder extends EJBObject{
public int add(int a,int b) throws RemoteException;
}
AdderBean.java
package com.brainysoftware.ejb;
import java.rmi.RemoteException;
import javax.ejb.EJBException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
public class AdderBean implements SessionBean{
public int add(int a, int b){
System.out.println("From AdderBean");
return (a+b);
}
#Override
public void ejbActivate() throws EJBException, RemoteException {
// TODO Auto-generated method stub
}
#Override
public void ejbPassivate() throws EJBException, RemoteException {
// TODO Auto-generated method stub
}
#Override
public void ejbRemove() throws EJBException, RemoteException {
// TODO Auto-generated method stub
}
#Override
public void setSessionContext(SessionContext arg0) throws EJBException,
RemoteException {
// TODO Auto-generated method stub
}
}
AdderHome.java
package com.brainysoftware.ejb;
import java.rmi.RemoteException;
import javax.ejb.CreateException;
import javax.ejb.EJBHome;
public interface AdderHome extends EJBHome{
Adder create() throws RemoteException, CreateException;
}
The deployment descriptor is as follows:
<?xml version="1.0" encoding="UTF-8"?>
<ejb-jar version="3.1" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/ejb-jar_3_1.xsd">
<description>Your first EJB application</description>
<display-name>Adder Application</display-name>
<enterprise-beans>
<session>
<ejb-name>Adder</ejb-name>
<home>com.brainysoftware.ejb.AdderHome</home>
<remote>com.brainysoftware.ejb.Adder</remote>
<ejb-class>com.brainysoftware.ejb.AdderBean</ejb-class>
<session-type>Stateless</session-type>
<transaction-type>Bean</transaction-type>
</session>
</enterprise-beans>
</ejb-jar>
I created a jar file of this project and placed the jar in the tomcat's lib.
Now, for the client I created a dynamic web project having the class BeanClient.java that uses the Adder bean:
import java.rmi.RemoteException;
import java.util.Properties;
import javax.ejb.CreateException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import com.brainysoftware.ejb.Adder;
import com.brainysoftware.ejb.AdderHome;
import javax.rmi.PortableRemoteObject;
public class BeanClient {
public static void main(String[] args){
Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
props.put(Context.PROVIDER_URL, "localhost:1099");
try{
InitialContext jnic = new InitialContext(props);
System.out.println("Get context");
Object ref = jnic.lookup("Adder");
System.out.println("Got reference");
AdderHome home = (AdderHome) PortableRemoteObject.narrow(ref,AdderHome.class);
Adder adder = home.create();
System.out.println("Adding 2 and 5:"+adder.add(2,5));
} catch(NamingException e){
System.out.println(e.toString());
} catch(CreateException e){
System.out.println(e.toString());
} catch (RemoteException e) {
System.out.println(e.toString());
}
}
}
On executing this class in eclipse, I get the following error:
Get context
javax.naming.CommunicationException: Could not obtain connection to any of these urls: localhost:1099 and discovery failed with error: javax.naming.CommunicationException: Receive timed out [Root exception is java.net.SocketTimeoutException: Receive timed out] [Root exception is javax.naming.CommunicationException: Failed to connect to server localhost:1099 [Root exception is javax.naming.ServiceUnavailableException: Failed to connect to server localhost:1099 [Root exception is java.net.ConnectException: Connection refused: connect]]]
Could you please help me out with this?
to look up and ejb firstbale :
you must have an interface and it's implementation.
you have to annotate your interface (#Local ou #Remote)
The implementation must be annotated #statless ou #statful
You have to add on you project a jndi.properties.
your ejb project must be deployed on your server to be easy to look up it.
i have for you an example with jboss here :
https://www.youtube.com/watch?v=mBwgHuBg96g
i hope that my answer is useful pour you

initiating error when trying to return a page with webdriver

I am writing a few testscripts and coming up with a initiating error of some sort when I run it. It keeps stating that the logintest should be void but it return another page. Any ideas-below is the code
package com.testscripts;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import org.junit.rules.ErrorCollector;
import static org.junit.Assert.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.PageFactory;
import com.helpers.setup;
import com.pages.Homepage;
public class TestCase1_login extends setup {
public TestCase1_login() throws Exception {
super();
// TODO Auto-generated constructor stub
}
public static boolean IsLogIn = false;
#Rule
public ErrorCollector errorCollector = new ErrorCollector();
#Test
public Homepage LogIntest() {
try {
System.out.println(System.getProperty("user.dir"));
driver.get("http://localhost:2020/Clockwise/Login.htm");
driver.findElement(By.id("USERNAME")).clear();
driver.findElement(By.id("USERNAME")).sendKeys("system");
driver.findElement(By.id("PASSWORD_EDIT")).clear();
driver.findElement(By.id("PASSWORD_EDIT")).sendKeys("clockwise");
driver.findElement(
By.xpath("//button[#onclick='return OkClick();']")).click();
Thread.sleep(3000);
}
catch (Throwable t) {
errorCollector.addError(t); // Assume.assumeNoException(t); // no
// testcases will be run if
System.out.println("LogIn Failure");
}
return new Homepage(driver);
}
}
HomePage.Java:
package com.pages;
import org.openqa.selenium.WebDriver;
public class Homepage {
private WebDriver driver;
public Homepage(WebDriver driver){
this.driver=driver;
}
}
It's because JUnit requires all test method (#Test) "must" be declared return type as "void".
You need to create one more page class for Login (ex. LoginPage) and create a login method that returns HomePage, then you can call it in your JUnit test class a below:
#Test
public void testLogin() throws Exception {
LoginPage loginPage = new LoginPage(driver);
HomePage homePage = loginPage.loginAs("system", "clockwise");
assertEquals("Login success verification done here",homePage.getLogingSuccessMessage());
}

Using EJBs in thread spawned from Servlet - bad practice?

We have a servlet as follows:
public class CacheRefresher extends HttpServlet {
private static final long START_TIMEOUT = 120*1000;
public void init(ServletConfig servletConfig) throws ServletException {
super.init(servletConfig);
new Thread(new Worker()).start();
}
private class Worker implements Runnable {
public Worker() { }
public void run() {
try {
Thread.sleep(START_TIMEOUT);
} catch (InterruptedException e) {
}
while(true) {
MyService myService = null;
try {
myService = ServiceFactory.getInstance().getMyService();
myService.doSomething();
} catch (Exception ex){
ex.printStackTrace();
}finally {
ServiceFactory.getInstance().releaseMyService(myService);
}
try {
Thread.sleep(timeout);
} catch (InterruptedException e) {
}
}
}
}
}
Its purpose is to periodically call a service. There will only be a single instance of this Servlet, which will be created on server startup. MyService is an EJB.
How bad is this? I know spawning threads from EJBs is not allowed, but what about the other way around? What will happen on server shutdown?
Conceptualy i dont see a problem with invoking ejb methods from multiple threads (even if you created the threads yourself). For the ejb-container that will be just another client among others.
From your example it looks like the soul purpose of you servlet is to start a bunch of timers. If you can use ejb 3.1, there is java ee standard way to do that.
First a Singleton ejb that launches the timers on startup
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.ejb.Singleton;
import javax.ejb.Startup;
#Singleton
#Startup
public class SingletonBean {
#EJB
LabBean labBean;
#PostConstruct
public void init() {
long interval = 4000;
long initialExpiration = 2000;
labBean.startTimer(initialExpiration, interval, "MyTimer");
}
}
Then a SLSB that handles the timeout:
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.ejb.Timeout;
import javax.ejb.Timer;
import javax.ejb.TimerConfig;
import javax.ejb.TimerService;
#Stateless
public class LabBean {
#Resource
protected TimerService timerService;
#Timeout
public void timeoutHandler(Timer timer) {
String name = timer.getInfo().toString();
System.out.println("Timer name=" + name);
}
public void stopTimer(String name) {
for (Object o : this.timerService.getTimers())
if (((Timer) o).getInfo().toString().startsWith(name)){
((Timer)o).cancel();
}
}
public void startTimer(long initialExpiration, long interval, String name){
stopTimer(name);
TimerConfig config = new TimerConfig();
config.setInfo(name);
config.setPersistent(false);
timerService.createIntervalTimer(initialExpiration, interval, config);
}
}

Resources