Using EJBs in thread spawned from Servlet - bad practice? - servlets

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);
}
}

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.

How to wait cancellation of task after Service#cancel?

Look at this example:
package sample;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.stage.Stage;
public class Main extends Application {
//NOTICE: This is class in **other file** (here is just for example)
private static class MyService extends Service {
#Override
protected Task createTask() {
return new Task() {
#Override
protected Object call() throws Exception {
System.out.println("Service: START");
while(true) {
System.out.println("Service: ITERATION");
// Thread.sleep(3000); // This raise InterruptedException after cancel, but how about such code (it won't raise exception):
for(long i = 0; i < 1_000_000_000; i++) {
}
if (isCancelled())
break;
}
System.out.println("Service: END");
return null;
}
};
}
}
#Override
public void start(Stage primaryStage) throws Exception {
MyService myService = new MyService();
myService.start();
Thread.sleep(5000);
myService.cancel();
System.out.println(myService.getState()); // Here is `CANCELLED` already but task isn't finished yet.
// <--- How to wait cancellation of Task here?
System.out.println("This command must be called after `Service: END`");
Platform.exit();
}
public static void main(String[] args) {
launch(args);
}
}
As you known call of Service#cancel doesn't wait cancellation of Task. So, I want to block main thread and await cancellation of Task. How can I do it?
P.S.
Looks like Service doesn't provide any callback/event handler to check real cancellation of Task. Is it right?
By default, Service.cancel() interrupts the Task. So an InterruptedException must be raised and your task will be terminated (forcefully).
One thing you could do is to store the created task in a global variable in your MyService class and override the cancel method like this:
class MyService extends Service {
private Task t;
#Override
public boolean cancel() {
if (t != null) {
return t.cancel(false);
} else {
return false;
}
}
#Override
protected Task createTask() {
t = new Task() { /* ... */ };
return t;
}
}
The rest will be easy. Add a change listener to the service state property (or use setOnCanceled() method) and do whatever you want to do after the state change, in the callback.
Never block the FX Application Thread.
The Service class does indeed define a setOnCancelled(...) method, which you use to register a callback:
myService.setOnCancelled(event -> {
System.out.println("Service was cancelled");
});
Note that when you cancel a Service, it will interrupt the thread if it is blocked. So if you don't catch the InterruptedException it will not exit the call method normally. This is why you don't see the "END" message.
Full example code:
import javafx.animation.PauseTransition;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.stage.Stage;
import javafx.util.Duration;
public class ServiceCancellationTest extends Application {
//NOTICE: This is class in **other file** (here is just for example)
private static class MyService extends Service<Void> {
#Override
protected Task<Void> createTask() {
return new Task<Void>() {
#Override
protected Void call() throws Exception {
System.out.println("Service: START");
while(! isCancelled()) {
System.out.println("Service: ITERATION");
try {
Thread.sleep(3000);
} catch (InterruptedException interrupted) {
System.out.println("Task interrupted");
}
if (isCancelled())
break;
}
System.out.println("Service: END");
return null;
}
};
}
}
#Override
public void start(Stage primaryStage) throws Exception {
MyService myService = new MyService();
myService.start();
myService.setOnCancelled(event -> {
System.out.println("In cancelled callback: "+myService.getState()); // Here is `CANCELLED` already but task isn't finished yet.
});
// You should never block the FX Application Thread. To effect a pause,
// use a pause transition and execute the code you want in its
// onFinished handler:
PauseTransition pause = new PauseTransition(Duration.seconds(5));
pause.setOnFinished(event -> {
myService.cancel();
System.out.println("After calling cancel: "+myService.getState());
System.out.println("This command must be called after `Service: END`");
Platform.exit();
});
pause.play();
}
public static void main(String[] args) {
launch(args);
}
}

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();
}
};
}
}
}

How to quickly stop seda in camel

I have a camel route with a splitter (using streaming) that sends messages to a seda queue to be processed. When I'm trying to stop the application gently, the seda queue doesn't stop immediately, it is processing all the messages before finally shutting down.
What can I do to stop it right away?
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.ExpressionBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.main.Main;
public class MySedaShutdownTest extends RouteBuilder {
#Override
public void configure() throws Exception {
onException(Exception.class)
.process(new Processor() {
#Override
public void process(Exchange exchange) throws Exception {
System.out.println("exception");
}
});
from("timer:myTimer?repeatCount=1")
.split(ExpressionBuilder.beanExpression(new MySplitter(), "myIterator"))
.streaming()
.to("seda:mySeda");
from("seda:mySeda")
.throttle(1)
.process(new Processor() {
#Override
public void process(Exchange exchange) throws Exception {
System.out.println("processing: " + exchange.getIn().getBody()
+ "; app status: " + exchange.getContext().getStatus());
}
});
}
public static class MySplitter {
public Iterator<String> myIterator() {
List<String> values = new ArrayList<String>();
for (int i = 0; i < 10; i++) {
values.add("string nr : " + i);
}
System.out.println("in myIterator");
return values.iterator();
}
}
public static void main(String[] a) throws Exception {
final Main main = new Main();
new Thread(new Runnable() {
#Override
public void run() {
try {
TimeUnit.SECONDS.sleep(4);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
System.out.println("invoking shutdown");
main.shutdown();
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
System.out.println("starting app");
main.enableHangupSupport();
main.addRouteBuilder(new MySedaShutdownTest());
main.run();
}
}
There is a purgeQueue method on the SedaEndpoint. So you can get the endpoint and call this method. You can also access it from JMX.
A bit related we have this ticket for improvement
https://issues.apache.org/jira/browse/CAMEL-5911
And I logged a ticket for this
https://issues.apache.org/jira/browse/CAMEL-6405
Just add string below as first line of your configure() method:
getContext().getShutdownStrategy().setTimeout(1);
It will reduce shutdown timeout from 300 seconds (default) to 1
See more info on controlling start-up and shutdown of routes.

Get exception when using injection with a simple HelloEJB project

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.

Resources