Well, I'm using Quartz to schedule some jobs that I need in my application. But, I need some way to access a Stateful SessionBean on my Job. I knew that I can't inject it with #EJB. Can anyone help me?
Thanks.
I used the EJB3InvokerJob to invoke the methods of my EJB. Then I created my jobs that extends the EJB3InvokerJob, put the parameters of what EJB and method it should call and then call the super.execute().
The EJB3InvokerJob can be found here: http://jira.opensymphony.com/secure/attachment/13356/EJB3InvokerJob.java
My Job is looking like this:
public class BuscaSistecJob extends EJB3InvokerJob implements Job{
private final Logger logger = Logger.getLogger(this.getClass());
#Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
JobDataMap dataMap = jobExecutionContext.getMergedJobDataMap();
dataMap.put(EJB_JNDI_NAME_KEY, "java:app/JobService");
dataMap.put(EJB_INTERFACE_NAME_KEY, "br.org.cni.pronatec.controller.service.JobServiceLocal");
dataMap.put(EJB_METHOD_KEY, "buscaSistec");
Object[] arguments = new Object[1];
arguments[0] = jobExecutionContext.getTrigger().getStartTime();
dataMap.put(EJB_ARGS_KEY, arguments);
Class[] argumentTypes = new Class[1];
argumentTypes[0] = Date.class;
dataMap.put(EJB_ARG_TYPES_KEY, argumentTypes);
super.execute(jobExecutionContext);
}
}
And my EJB is like this:
#Stateless
#EJB(name="java:app/JobService", beanInterface=JobServiceLocal.class)
public class JobService implements JobServiceLocal {
#PersistenceContext
private EntityManager entityManager;
#Resource
private UserTransaction userTransaction;
#Override
public void buscaSistec(Date dataAgendamento) {
// Do something
}
I expect to help someone.
A simple solution would be to lookup the EJB via JNDI in the Job implementation.
final Context context = new InitialContext();
myService= (MyService) context
.lookup("java:global/my-app/myejbmodule-ejb/MyService");
I have done this in a current application I am developing on Glassfish 3.1.
you can do that simply by lookup the EJB via JNDI in the Job implementation. In particular, the JNDI name will be:
mappedName#name_of_businessInterface
where name_of_businessInterface is the fully qualified name of the business interface of this session bean. For example, if you specify mappedName="bank" and the fully qualified name of the business interface is com.CheckingAccount, then the JNDI of the business interface is bank#com.CheckingAccount.
Code Example:
Context context = new InitialContext();
MyService myService= (MyService) context.lookup("MyService#com.test.IMyService");
Related
I have started a Quarkus project and i have there 2 tables, i am trying to run a Method immediately after deploying, In the method i use Entitymanger to save some results in the database.
In pure Jakarta EE, you could an EJB and annotate it with #Startup. But Since quarkus uses CDI.
#ApplicationScoped
public class StartApp {
private static final String PERSISTENCE_UNIT_NAME = "Employee";
public void init(#Observes #Initialized(ApplicationScoped.class) Object init) {
EntityManagerFactory factory =
Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
EntityManager em = factory.createEntityManager();
Directory directory = new Directory("/some/info", true, false, ".xml");
em.persist(directory);
em.close();
}
}
How can i do that!? some guess !
I think what you need is this:
#ApplicationScoped
class StartApp {
void startup(#Observes StartupEvent event) {
// Do whatever needs to be done.
}
}
More information and options can be found on the very well documented quarkus pages. https://quarkus.io/guides/cdi-reference#startup-event
Ps. don't forget about your transactions and maybe take a look at Hibernate ORM.
there's a session scoped bean 'Identity' which I injected in a #Stateless bean which implements Runnable:
#Stateless
#LocalBean
public class Test implements Runnable {
#Inject
Identity identity;
#Inject
Logger log;
#Override
public void run() {
log.warn("Test: " + this + " " + identity.getAccount().getId());
}
}
There's also a bean which invokes the above Runnable asynchronously:
#Stateless
#LocalBean
public class BeanContextExecutor implements Executor {
#Asynchronous
#Override
public void execute(Runnable command) {
command.run();
}
}
and finally, the invocation looks like this:
#Stateless
public class OtherBean {
#Inject
BeanContextExecutor executor;
...
executor.execute(command);
...
}
When running this I'm getting the following error:
...
Caused by: org.jboss.weld.context.ContextNotActiveException: WELD-001303: No active contexts for scope type javax.enterprise.context.SessionScoped
...
Is there any way to propagate the SessionContext to the background thread?
I also tried to submit this Runnable to ManagedExecutorService and even to create a proxy for it with a ContextService and submit a proxy but still getting the same error.
Thanks for any help with this!
As a workaround in BeanContextExecutor I used BoundSessionContext to create a dummy session context for a new thread and also had to manually copy the required session bean to make its state available in the background thread:
#Inject
BoundSessionContext boundSessionContext;
// Backed by a ConcurrentHashMap<Runnable, Identity> which stores the state of the session scoped bean before spawning a new thread
#Inject
GlobalExecutionContext globalExecutionContext;
#Inject
Instance<Identity> identityInstance;
#Inject
Cloner cloner;
#Inject
private BeanManager beanManager;
#Asynchronous
#Override
public void execute(Runnable command) {
HashMap<String, Object> storage = new HashMap<>();
boundSessionContext.associate(storage);
boundSessionContext.activate();
Identity identity = globalExecutionContext.remove(command);
Bean<Identity> bean = (Bean<Identity>) beanManager.resolve(beanManager.getBeans(Identity.class));
Identity localIdentity = beanManager.getContext(bean.getScope()).get(bean, beanManager.createCreationalContext(bean));
cloner.copyPropertiesOfInheritedClass(identity, localIdentity);
command.run();
boundSessionContext.invalidate();
boundSessionContext.deactivate();
boundSessionContext.dissociate(storage);
}
The example is intended to demonstrate the approach, it's possible to improve it like support passing beans of an arbitrary type. But I don't like this approach at all. There should be a better solution for context propagation problem.
Update:
I'd like to keep the caller identity in a background thread even if initial session is expired, it looks like the above solution is suitable for this.
I am a long time Seam user who tries to move to Java EE7, JSF2.2 and CDI now.
In Seam you tend to use EntityManagers with extended scope most of the time (in the Seam Conversation Scope). You don't get any LIEs on Ajax request etc.
I am trying to do it in a similar way with Java EE7 and CDI but somehow the injected EntityManager is only transaction scoped. When I get a ajax request in the entities that were loaded before are not managed anymore.
I am using the new javax.faces.view.ViewScoped and javax.transactional.Transactional on my CDI bean.
My Producer:
#PersistenceContext(unitName = "primary", type = PersistenceContextType.EXTENDED)
private EntityManager entityManager;
#Produces
#Default
#Dependent
public EntityManager getEntityManager() {
return entityManager;
}
And my CDI bean:
#Named
#ViewScoped
#Transactional
public class TestBean implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
#Inject
EntityManager entityManager;
Logger log = Logger.getLogger(TestBean.class);
private TestEntity lastTest = null;
public void testAdd(){
TestEntity test = new TestEntity();
test.setVal("Test "+System.currentTimeMillis());
entityManager.persist(test);
entityManager.flush();
log.infov("Created test entity {0}", test);
lastTest = test;
}
public void testRead(){
List<TestEntity> test = entityManager.createQuery("select t from TestEntity t").getResultList();
for(TestEntity t: test){
log.infov("Found {0} managed {1}",t,entityManager.contains(t));
}
if(lastTest!=null){
log.infov("Last Test {0} managed {1}",lastTest,entityManager.contains(lastTest));
}
}
So when I first call testAdd() via Ajax it creates a new test entity. When I then call testRead() it gets all test entities and checks that the last created test entity is still managed (which it should if it is an EntityManager with an extended persistent context). But entityManager.contains(lastTest) always returns false.
What am I doing wrong?
I believe I can't use #PersistenceContext directly in the CDI bean. So how do I get the desired (Seam like) behaviour?
When you specify that an injected EntityManager is an extended persistence context, all object instances remain managed. Extended persistence contexts can only be used within Stateful session beans.
This is according to JBOSS documentation: https://docs.jboss.org/ejb3/app-server/tutorial/extended_pc/extended.html.
Consider packaging your insert/update/delete operations into EJBs while simple read from database can be through CDI beans. But more complex operations involving multiple reads and writes as well as transaction should be within EJBs.
I'm trying to inject a local #Stateless EJB into a Rest exception handler but getting the following error.
javax.naming.NameNotFoundException: Name [Test] is not bound in this Context. Unable to find [Test].
The maven Web project is running on Apache-tomee-1.7.1-jaxrs.
The EJB:
#Stateless(name = "Test")
public class Test {
public void sayHello() {
System.out.println("Hello");
}
}
The Exception handler which from my understanding I must treat as a client to the EJB.
#Provider
public class TestExceptionHandler implements ExceptionMapper<Throwable> {
#Context
HttpServletRequest request;
#Override
public Response toResponse(Throwable throwable) {
InitialContext context;
try {
context = new InitialContext();
Test test = (Test) context.lookup("Test");
test.sayHello();
} catch (NamingException ex) {
ex.printStackTrace();
}
return Response.ok().build();
}
}
I have also tried to do the following for the lookup: context.lookup("java:comp/env/Test");
The http://openejb.apache.org/jndi-names.html documentation is very difficult to understand.
Also tried the following which was my first attempt. http://blog.iadvise.eu/2015/06/01/jee-using-ejb-and-context-annotations-in-a-jax-rs-provider-class/
Am I missing any configuration in the tomee server or in my code?
The java:comp/env namespace is for the EJB references, not EJBs. You have not declared an EJB reference anywhere.
It's probably easiest to directly look up the EJB using lookup("java:module/Test") (assuming the EJB is packaged in the war, otherwise, java:app/ejbmodname/Test) because JAX-RS does not support EE injection by default. To declare an EJB reference, you would need to make the provider class an EJB itself or a CDI class (add beans.xml to the module), and then declare a field as #EJB(name="Test") Test myBean;.
Is it possible to #Inject a stateless session bean into a subclass of AuthenticatorBase?
I'm using JBoss as 7.1.1.
My code looks like this:
...
public class myValve extends AuthenticatorBase {
#Inject AuthController controller;
//some code ...
}
Using the controller object leads to NullPointerException.
If controller is null it means that the myValve object itself was not injected.
It is possible to add an existing object to the CDI context retroactively, for example with this code:
public <T> void addToCDI(T object) {
BeanManager beanManager = BeanManagerProvider.getInstance().getBeanManager();
AnnotatedType<T> annotatedType = beanManager.createAnnotatedType((Class<T>)bject.getClass());
InjectionTarget<T> injectionTarget = beanManager.createInjectionTarget(annotatedType);
CreationalContext<T> context = beanManager.createCreationalContext(null);
injectionTarget.inject(object, context);
}
After the execution of this code the injections have been performed.