Possible JNDI lookups within EJB container - java

I'm going through the EJB 3.1 spec and am trying to grasp the different possible ways a JNDI call can be made.
You can do it using a SessionContext and an InitialContext (or a self-created context based on the Initial- or SessionContext).
Based on which you use the syntax differs, but I can't seem to find the logic behind it.
So my question is: when can I use what syntax to use JNDI calls within an EJB container environment?
The rest of this question just serves as illustration of my point.
For example, I believe this is always possible for a correctly injected sessioncontext or created initialcontext:
ctx.lookup(java:global[/<app-name>]/<module-name>/<bean-name>[!<fully-qualified-interface-name>])
ctx.lookup(java:comp/env ...)
// special ones like these
ctx.lookup("java:comp/UserTransaction");
ctx.lookup("java:comp/ORB");
Sometimes (only for session context?) this shorter version is possible:
ctx.lookup(<bean-name>);
What about in an embedded environment, can only global references be used?

I usually inject EJBs inside EJB container with #EJB annotation. So the JDNI look ups are done by the server at deploy time.
For example JBOSS deployment:
INFO [org.jboss.as.ejb3.deployment.processors.EjbJndiBindingsDeploymentUnitProcessor] (MSC service thread 1-2) JNDI bindings for session bean named TestBean in deployment unit subdeployment "MyEJB.jar" of deployment "MyProject.ear" are as follows:
java:global/MyProject/MyEJB/TestBean!my.project.TestBean
java:app/MyEJB/TestEJB!my.project.TestBean
java:module/TestEJB!my.project.TestBean
java:global/MyProject/MyEJB/TestEJB
java:app/MyEJB/TestBean
java:module/TestBean
Some are per EJB specification some are application server dependent.
If you have to make look ups from context I think the best way is to use java:global.
You can also find some additional info at: http://glassfish.java.net/javaee5/ejb/EJB_FAQ.html#POJOLocalEJB

jndi is a bit like a file system. You can refer to things using a relative path based on where you are in the tree (where you "cd"-ed to).
The injected session context is by default "positioned" on java:comp, so there you reference things that are available in java:comp, without the need to provide the "full path".
Note that java:comp itself is relative to a single EJB bean, or because of historical reasons to the entire Web module.
I'm not 100% sure what you mean with embedded environment, but if the code from which you are doing the JNDI lookup is not part of any of the predefined scopes (like java:module, java:app, etc) only java:global can be portably used.

Related

What's the relation between CDI and JNDI service?

As far as I understand "pre-CDI" EJB and resources injection solutions (#EJB, #Resource and others, to be clear) use the JNDI service to locate objects "known" to the container by virtue of being JNDI registered, and then inject them where requested.
CDI, instead, relies on bean-discovery-mode parameter (ALL or ANNOTATED) to discover beans that need to be managed. But how is this process actually performed? A runtime scan of... what? Is JNDI not involved at all?
I have the feeling I'm getting something wrong about the whole mechanism...
The bean discovery process is described in detail in the CDI specification. Basically, the CDI container scans bean deployment archives for classes with certain annotations.
JNDI is not involved at all. Unlike EJBs, CDI beans cannot be looked up via JNDI in general.
Only the BeanManager itself can be looked up under the name of java:comp/BeanManager, but this is almost never required, unless you need to access managed beans from unmanaged code.

Does OSGI JNDI allow coexistence with JNDI calls from non-OSGI code?

Chapter 126 of the OSGI Enterprise Release 5 specification mentions compatibility:
"Support the traditional JNDI programming model used by Java SE and Java EE clients."
and use of OSGI-unaware code:
"Clients and JNDI Context providers that are unaware of OSGi use static methods to connect to the
JRE JNDI implementation. The InitialContext class provides access to a Context from a provider and
providers use the static NamingManager methods to do object conversion and find URL Contexts.
This traditional model is not aware of OSGi and can therefore only be used reliably if the consequences
of this lack of OSGi awareness are managed."
but it is not clear to me if this text only applies to "legacy" code executed inside an OSGI bundle, or also to code outside the OSGI container, f ex in a scenario where the OSGI container is embedded in an application.
In an embedding scenario, there may be application code both outside and inside the OSGI container that performs JNDI calls, and as they execute in the same JVM they will share JNDI implementation.
Question: Should an OSGI JNDI implementation running in an embedded OSGI container allow OSGI-unaware code outside the container to perform its JNDI calls like usual, or is some porting to "OSGI-awareness" required?
Trying this out myself with Apache Karaf 2.3.0 (which uses Apache Aries JNDI 1.0.0) this doesn't seem to work, as Apache Aries requires JNDI client calls to originate from an OSGI bundle.
Partial stacktrace:
javax.naming.NoInitialContextException: The calling code's BundleContext could not be determined.
at org.apache.aries.jndi.OSGiInitialContextFactoryBuilder.getInitialContext(OSGiInitialContextFactoryBuilder.java:46)
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:684)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:307)
at javax.naming.InitialContext.init(InitialContext.java:242)
at javax.naming.InitialContext.<init>(InitialContext.java:192)
Question: Is this correct behaviour, or is there a section of the specification I can refer to that is violated by this limitation?
I ran into same issue when trying to deploy Apache Karaf on Weblogic.
We use karaf through a servlet bridge - a war is deployed in weblogic which bridges all http requests to karaf.
I am running with the the following applications on weblogic:
app1 (uses JNDI)
app2
karaf-bridge (bridges requests to Karaf)
As soon as karaf starts the Aries JNDI implementation running inside Karaf sets InitialContextFactoryBuilder inside javax.naming.NamingManager to its own implementation. NamingManager holds a static reference to the initial context factory builder, so whichever implementation, irrespective of whether its running in an OSGI environment, sets this static reference becomes the JNDI provider.
In my case when app1 (non-OSGI) tries to do a new InitialContext, Aries JNDI tries to resolve it using the BundleContext and fails.
I fixed this using some very ugly hacks that involved extracting the javax.naming package from jre and installing it as a bundle in karaf.
So the answer to your question: I think the issue is really in the jre and not with OSGI on how JNDI lookup is managed.
I'm not sure if I understand the problem correctly... JNDI is a Service Provider Interface, and it needs some underlying implementation to run with. All you need to do is to provision it the OSGI container.
I would recommend creating single bundle with all jars needed by JNDI and export all packages. Then use Dynamic-Import: * to use it. It worked in our case (Eclipse RCP application with JBoss 5 JNDI used for EJB calls).
However if you need JNDI inside and outside of the container and you don't want to struggle with Classloading, I would recommend adding all jars to the applications classpath. This way it should be accessible in whole your application.
Apache Aries seems to have thought about this and have provided an implementation of JRE initial context factory builder (org.apache.aries.jndi.JREInitialContextFactoryBuilder) which seems to work. However, for this to work, I had to change Aries code that registers the JVM wide initial context factory builder. There may be another (and possibly better) way of achieving this. But this seemed to work.
Also, note that the problem does not stop at InitialContextFactoryBuilder being set in NamingManager. The same issue arises for ObjectFactoryBuilder (which is again set JVM wide in NamingManager). Depending on the JNDI provider you are trying to connect to, you may need to change that part of Aries JNDI code as well. e.g. for Tibco EMS JNDI connection, I had to tweak the code for OSGiObjectFactoryBuilder from Aries to return a Tibco specific ObjectFactory. This can be easily generalized using Context.OBJECT_FACTORIES environment value.
I've raised a JIRA for the same - https://issues.apache.org/jira/browse/ARIES-1127

Initializing Memcached/JDBC Resources for a JAX-RS servlet

I have a service where I want to maintain data persistence in a mysql db using jdbc. While i have experience building jdbc apps and jax-rs apps in isolation, I've never combined the two. The question is, where does the build up and tear down required for the jdbc-type stuff go? Ordinarily i'd put the build up in a static block, or in a constructor, and id have have a cleanup method that gets called in a finally. this doesnt seem to work in the jax-rs framework- the constructor gets called at every invocation, and there is no place to my knowledge to put any clean up methods. unfortunately, there are sparse examples for combining the two technologies online, something i find surprising. Can you guys help me out?
As a general rule, to do things at the startup and shutdown of your web application, you should create custom ServletContextListeners and list them in your web.xml.
With JDBC resources in a WAR, often times you have your container (e.g. Tomcat, Websphere, etc.) create and manage a connection pool which can be shared with a number of web applications. You would define a resource-ref for a javax.sql.DataSource in your web.xml. Then there is a container specific method for defining and binding the JDBC DataSource to the resource-ref of your application.
I'm not familiar with Memchached and what is needed on startup/shutdown so this is only a guess. If you need to register/unregister with a Memcache server you might try having one or more env-entry tags defined in your web.xml which could be used by a custom ServletContextListener to do your bidding.

DI in an EJB/MDB Application

I'm currently developing a small EJB application running on IBM Websphere Application Server 7 (Java EE 5). The app mainly consists of one MDB listening for incoming MQ messages which are transformed and stored in a DB. Currently I'm using a lot of Singleton/Factories to share configurations, mappings, datasource lookups etc. But this actually leads to some very hard to test code. The solution might be using a (simple) DI framework like guice/spring to inject the different instances. The question is: Where to place the initialization/ setup code? Where is the main entry point of the application? How can I inject instances into the MDBs?
it might be worth looking at backing off from using Guice, and trying to work with the injection mechanisms already available with Java EE 5.
Regarding finding a suitable "startup point", unfortunately the EJB specification does not define a way where you can have a bean run at startup. However, the web profile of the EE spec does have one -- you can add a WAR to your application, and set a servlet listener component:
http://java.sun.com/javaee/5/docs/api/javax/servlet/ServletContextListener.html
You can set this to start whenever the application is loaded and started by the container (WebSphere). Watch out for classloader issues though.
Using Spring, you can do it via EJB3 interceptors, see http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/ejb.html#ejb-implementation-ejb3
Useful info on caveats are in the javadoc, make sure you read it: http://static.springsource.org/spring/docs/3.0.x/api/org/springframework/ejb/interceptor/SpringBeanAutowiringInterceptor.html

Making sense of JPA and EJB3 and WebServices

I'm just getting started with JPA, creating stateless session beans from the JPA entities, then accessing the beans through a web service. While I have a lot of experience developing database backed web services "the old way", I have some questions about what's going on behind the scenes with this new "annotation driven approach".
What I see is, NetBeans sort of directs you to build applications in this manner though their wizards.
Create an Enterprise Application with EJB and Web Application modules.
Create Entity classes. I created mine from an existing database.
Create session beans from the entity class.
Create Web services from the session bean.
It all looks pretty simple, but what's going on behind the scenes? Specifically:
I see that the web service (created with the #WebService annotation) references my stateless session bean (using the #EJB reference).
What happens here? Does it just grab an instance of the EJB from the application server's EJB pool?
Nevermind. I was thinking of an instance where there was more than 1 table - meaning more than 1 type of Entity class and more than 1 type of EJB. I was looking at the web service and just seeing the #EJB reference and didn't understand who it was getting the bean type from that annotation. Just below that however, it the reference to the local bean interface - so that's that.
If there is more than 1 type of EJB deployed to the server, how does it know which one to grab?
The EJB is defined via the #Stateless and #Local annotations. The bean implementation references an EnityManager via the #PersistenceContext annotation.
Where is the jndi lookup to the database done (maybe in the persistence.xml file)?
Do all of the EJBs share a common EntityManager (assuming the EntityManager is thread safe)? If not, I know that the EnityManager utilizes a second level cache to help reduce trips to the database, are these caches somehow kept in sync?
I know this is a lot of questions, but they're all sort of related and there seem to be a lot of complicated concepts for something that's so easy to build through the wizards. I want to make sure I understand what's all going on here.
Thanks in advance!
What happens here? Does it just grab an instance of the EJB from the application server's EJB pool?
A JAX-WS web component endpoint (as opposed to a JAX-WS EJB endpoint) follows the typical servlet threading model, which means that typically there is one instance that is executed concurrently for each client. JAX-WS implementations are free to leverage pools of bean instances to handle a request in a fashion similar to stateless session EJB components. (source: Developing Applications for the JavaTM EE Platform FJ-310).
In all cases, it is fine to inject/look-up stateless beans because the container guarantees that the beans will always be thread safe. In affect, the container automatically serializes clients calls but uses instance pooling to make sure you still get concurrency benefits.
If there is more than 1 EJB deployed to the server, how does it know which one to grab?
Hmm... I didn't get this one. Can you clarify what you mean exactly? Why would there be any ambiguity?
Where is the jndi lookup to the database done (maybe in the persistence.xml file)?
In a Java EE environment, you specify your data source in a <jta-data-source> element in each persistence unit of the persistence.xml file (which can contain several persistence units) and the data source will be obtained by the EntityManager (only when needed, i.e. only if a data access is really needed).
Do all of the EJBs share a common EntityManager?
No. The EntityManager is a non-thread-safe object that should be used once, for a single business process, a single unit of work, and then discarded. In a Java EE environment using EJB 3, the default pattern is "entitymanager-per-request". A request from the client is send to the EJB 3 persistence layer, a new EntityManager is opened, and all database operations are executed in this unit of work. Once the work has been completed (and the response for the client has been prepared), the persistence context is flushed and closed, as well as the entity manager object. (source: Chapter 4. Transactions and Concurrency).

Categories

Resources