How to inject a CDI managed bean that exists in another classloader - java

I am working on a framework which will be used in Java EE applications and therefore is likely to be deployed in the \lib directory of an EAR file.
The framework will use CDI to programmatically lookup and inject beans that are located in the Java EE application that is using the framework. The problem I've got is when the Provider.get() method from javax.enterprise.Provider<T> is called by my framework to get an instance of the bean, Weld throws a UnsatisfiedResolutionException.
To check this isn't an issue related to CDI I've also tried using MyClass myClass = Class.forName(clazz).newInstance(); to get an instance of the class but a ClassNotFoundException is thrown.
The structure of EAR file I'm using for testing purposes is as follows:
MyTestApp.ear
+\lib\MyFramework.jar <----Contains the framework invoking the Provider.get() method
+MyTestApp.jar <----Contains the bean I want to inject
My test application's EAR contains an application.xml file which includes <library-directory>lib</library-directory>.
I believe this problem is occurring because the bean I want to inject exists in a separate classloader. i.e. \lib\MyFramework.jar is in a different classloader to MyTestApp.jar. I found this SO question which seems to suggest this is the case. Given that I'm developing a framework I don't believe the answer in the question is a viable solution for my needs.
I'm intrigued to find out whether creating a CDI portable extension would allow me to get an instance of the bean I want to use, but don't have enough experience in this area. Using #Observes ProcessAnnotatedType<T> I can see beans that exist outside of the \lib directory in an EAR file, including the ones I want to programmatically inject.
My questions are:
Am I correct in assuming this problem is occurring because \lib\MyFramework.jar and MyTestApp.jar are in separate classloaders?
Is there anything I can do using CDI that will allow my framework when deployed in the \lib directory of an EAR file to make the Provider.get() method call to avoid Weld throwing a UnsatisfiedResolutionException?
Is there anything I can do outside of CDI to achieve same result?
Update
I've now tried moving MyFramework.jar to the root of the EAR file and also including the jar module in the application.xml file but the container fails to start the application due to a CDI unsatisfied dependency exception. The bean referenced in the exception can be injected when MyFramework.jar is located in the \lib directory and is a different bean to the one referenced in my question.

1 : yes
2 : actually I don't know
3 : Yes, you must understand the ear classloader hierarchy, the jars in ear lib directory are loaded at the ear level and so available in all child classloaders (there is one child classloader per component in the ear).
It means that MyFramework.jar is visible from MyTestApp.jar ear child classloader but the inverse is false.
see In java EE, which jars should I put in the library dir?
You can either :
move MyTestApp.jar to ear lib directory (MyFramework.jar can be either in lib dir and reference MyTestApp.jar or at ear root)
move MyFramework.jar at ear root and reference MyTestApp.jar in its manifest classpath
see Deployment of multiple, depended CDI jars in one EAR

It seems to me that it might be a poor architectural decision to have your "framework" depend on your application implementation. Perhaps it should be that your application that implements some framework-level interface to achieve your goal. As you have it, or would like it to work, suggests that an application, any application really, in your ear could influence the operation of all other applications in your ear by providing implementation to the framework. This seems like a bad idea to me. And if you were able to make this work and more that one application in your ear provided this implementation, CDI may still fail because of ambiguous dependencies.
There may be some container specific dependency configurations that you might be able employ. WildFly, for example, allows you to configure module-to-module dependencies. I think, it might be possible, in WildFly, for an ear to depend on a war.
While the above might work, after thinking about it, I this it is also a bad idea. You should really take a hard look at what you are really trying to do. I think if you take a harder look at what you are trying to do, you will discover that your will probably be able to peal out or abstract some dependencies and still provide implementation to the framework, but not from the applications in the ear.

Related

How to dynamically load jar files with application context by Spring (with no OSGi)?

I am going to create Java Application that can load external jar files at runtime by FileChooser. I am using Spring Framework, and I want to load jar file and its applicationContext.xml file and inject its dependencies dynamically. I tried to achieve this by OSGi, but it seems very complicated so that I am searching another appropriate variants.
I want to make something like Intellij IDEA plugin installation from the disk.
How can I do this? (After the jar file chosen restarting an application also accepted)
I realy like your approach, unfortunately spring has lifecycles that are strict. As you might know, spring autowires "beans" only. Exactly one lifecycle registers the different bean candidates. After that lifecycle spring (by default) does not accept new classes.
You must use the spring-osgi.
If you only need the CDI part out of spring, you might like to use a different CDI like red hat's jboss server.

CDI extension, how to know the Application name that a bean belongs to

I am new to CDI and I am writing a new CDI portable extension. My CDI extension will listen to events that are fired by the CDI container. I was wondering if there is a way to tell the name of the application that a class belongs to and what are the events that would provide that information.
by application I mean a ear application archive that is deployed on an application server. My goal is to create an extension that looks into applications deployed and for each add an annotation on some of it's classes. Each application classes would have a unique annotation. Example if we have app1 and app2 deployed on an app server. I want to create an extension that would annotate all/some classes contained in app1 with with #x1 and all classes of app2 with #x2 and so on.
To my knowledge, there is no concept of application in CDI. There are only bean archives. You might be able to determine that - e.g. WAR1 will be a different bean archive than WAR2 which in turn will be different than EAR/lib.
BUT, and I cannot stress this enough, the bean archive concept is interpreted slightly differently in Weld and OWB (as CDI implementations) so sticking to this would make in unportable (which probably won't matter since all servers except TomEE use Weld anyway). Truth be told, to even get hold of a bean archive, you might have to rely on Weld API (not just CDI).
But I think it would be wiser to find another way around this - why are you trying to achieve this? What gain is there in annotating beans differently in different archives? Because #Nikos has a good point with class loading. There is a whole new level of mess with EARs and you won't "see" some bean from other archives anyway (as per Java EE umbrella spec).

Can multiple portlets share a singleton? [duplicate]

I have a couple of Singleton classes in a Liferay application that hold several configuration parameters and a ServiceLocator with instances to WebServices I need to consume.
I have put these classes in a jar that is declared as a dependency on all my portlets.
The thing is, I have put some logging lines for initialization in theses singleton classes, and when I deploy my portlets I can see these lines multiple times, once for every portlet, since each portlet has its own class context.
For the AppConfig class it might not be such a big deal but my ServiceLocator does actually hold a bunch of references that take a good bit of memory.
Is there any way that I can put these Singleton references in some kind of Shared context in my Liferay Portal?
The problem is that every Portlet runs in its own WAR file and aech war file has its own classloader.
Usually when I had to achieve a requirement like this, I had to put the Singleton classen in a JAR file and this JAR file in the common class loader library instead of packing it into each WAR. (In Tomcat: <tomcatHome>/common/lib or something like that)
Then you'll also have to put all dependent libraries into that common lib dir, too. Don't know how to do that in Liferay, though. For tomcat see this thread: stackoverflow.com/questions/267953/ and this documentation: http://tomcat.apache.org/tomcat-7.0-doc/class-loader-howto.html. Depends on the Servlet container.
Alexander's answer gives the general answer that's true with or without Liferay in mind.
Liferay (as you mention it) adds another option to this: ServiceBuilder. You'll end up with the actual instances contained in exactly one web application, and you'll have an interfacing jar that you can distribute with every dependent application. This way you can more easily update your implementation: It's easy to hot-deploy new and updated web applications to your application server - it's harder to update code that's living on the global classpath.
The global classpath (Alexander's answer) however brings you immediate success while ServiceBuilder comes with its own learning curve and introduces some more dependencies. I don't mind those dependencies, but your mileage might vary. Decide for yourself
With maven portlet you can make a common Spring component and import in the pom of each portlet.
Another solution is to use service builder.
Spring MVC portlet would be the most recommended for this.

NoClassDefFoundError when trying to load class

I am getting a java.lang.NoClassDefFoundError when trying to instantiate some class
I will try to simplify the structure of my projects: I have 2 jar files A (with a.class inside) and B (with b.class) I am trying to instantiate a 'b' class inside 'a' code. JAR A is dependant on JAR B. JAR A is a regular JAR file which is located in application/lib and JAR B is packaged as an EJB_JAR.
I am using glassfish and J2EE with maven I am new to J2EE and I have tried to look up a little for it. I have figured out it might be a class loaders issue, as the Classloader that loads classes from lib ( A) is the Ancestor of the Classloader that loads EARs WARs and EJB_JARs hence because of visibility issues I cannot load class 'b' from 'a'
Also, when I'm trying invoke (using the "expression evaluator") Class.forName("com.package.SomeClass") in the debugger from classes located in Jar-A to load class in JAR-A I get a class, but when I try to load classes located in Jar-B I get the java.lang.NoClassDefFoundError exception.
The thing is, that the passed EJB in the constructor has all the EJB fields properly, so I thought it should work, and, everything was compiled successfully.
How do I solve this problem?
The weirdest thing:
I am using drools which resides in JAR_A and JAR_A has some regular class which tries to call b.class (in JAR_B)
calling b.class from a.class doesnt work,
but calling b.class directly from a rule (which got b.class from CommandFactory.newSetGlobal("Bclass",b))works just fine.
How Could it be?
when I pass it as an Object from JAR_B it works and invokates fine.
Recap
You say:
I am trying to instantiate a 'b' class inside 'a' code. JAR A is dependant on JAR B. JAR A is a regular JAR file which is located in application/lib and JAR B is packaged as an EJB_JAR.
From what I understand, you have a pom.xml to build jar A, which states that jar B is its <dependency/>.
Then I see two possible cases for your deployment scenarios: you are either deploying the jars to the application server as an EAR, where jar A is contained inside this EAR as a library and jar B is a deployment inside it, or you are trying to use B from another, unrelated application.
In either deployment case, this is an error, but it might be due to expressing your dependencies incorrectly, or accessing the EJB incorrectly.
Nested Deployment case
If this is a nested deployment, where jar A is contained in the EAR as a library, you have a dependency expression problem. An EAR library can not have a dependency on the EAR itself, it can only be the other way around. After all, this is the definition of a library, right? :)
You have to refactor your application to match the use case you are trying to implement here. For more info, see the excellent Patterns of Modular Architecture RefCard from DZone.
Application client case
If what you are writing is an isolated (might even be a standalone) client that is going to invoke some operations on the EJB, what you should do is create an interface (local or remote, depending on how you are deploying the client) and package it with the client application and your EJB.
Then use a JNDI lookup in your client application to obtain a reference to the remote EJB and use it via the interface:
Context foo = new InitialContext(remoteJndiServiceProperties);
MyBeanInterface bar = (MyBeanInterface)foo.lookup("com.mycompany.MyBeanInterface");
bar.doStuff();
The remote JNDI registry properties and your bean's business interface name have to be expressed properly, of course. See the EJB FAQ for Glassfish for more info.
It is even simpler if your client is running in the same deployment unit - you can just use the #EJB annotation in that case and inject a no-interface EJB reference.
For more information on standalone clients with GlassFish, see the Developing Application Clients with ACC guide which covers all possible deployment scenarios.
Some theory behind this
Run the application in a debugger (or look at the heap dump taken while your client is invoking methods on the EJB, passing it objects as parameters).
What you will see is that the EJB container (that is, your EJB) is not working with the actual class you think it is, but rather with something called a static proxy class, which is generated on the fly by the container.
Because of this, when you invoke the instanceof operator inside the EJB, checking if the class you're working with is of the correct type, it will evaluate to true, but when you try to typecast it, you will get a ClassCastException.
This is required by the EJB specification and there is not much you can do about it, except pass the objects not as references, but rather as serialized data (which is going to cost you).
It works the other way around, too, because the container must be able to intercept anything done to the EJB from outside of it, and react (such as unauthorized use of restricted methods, transaction handling, etc.).
BTW, a lot of what you are describing above is illegal. ;)
Manually loading classes using Class.forName() inside an EJB container, for example - the EJB container should manage the lifecycle of your objects and anything you can not obtain using a factory method, or even better, using "compatible" mechanisms such as CDI producers and dependency injection, should be passed to your EJBs as a parameter.
What is also questionable is the way you try to pass an instance of the EJB to an application running outside of the container. If you need to access your EJBs to invoke methods on them, you should do it by means of an EJB client, in your case most probably through a remote interface.
Also, look up the definition of classloader hell if you still want to pursue your approach - you might want to start with this article, but I guess it's just as good as any other.

How does a web server/container treat a POJO in respect to other classes like EJB's and Entities?

I'm trying to use plain old java objects(POJO)'s and regular class files where needed and only use EJBs when I need the functionality that they add such as asynchronous calls, pooling, etc. I'm wondering how the server treats this behavior once the project is deployed on a server. Since it is not managed by the container does a new instance have to be created for every stateless session bean pooled that might call one of it's methods? How do things like static methods or state affect this model.
Edit:
1) I can clarify more. The point of Java EE is that you annotate a POJO with #stateless etc so that a container can manage it. You don't have to declare a new instance of a stateless bean you just inject and can make calls to it's type.
2) Most Java EE tutorials and books never mention non annotated classes as a part of your business logic. It's never brought up. This seems strange to me if you can use them in Java EE projects for your business logic and it can get deployed on a server. If you don't need pooling or asynchronous access--the things that a container helps manager through an EJB then you can use theses regular POJO's in your Java EE project.
3) that leads me to my question which is how do I incorporate properly into a project? Do I put them in the EJB project that's connected to an EAR or should they go in the EAR? or Dynamic web project. There is almost no mention or instruction on proper use of regular objects like this. When it gets compiled into a WAR for deployment are there any issues you run into on the server? Isn't it expecting properly annotated EJBs, servlets or JSP?
The don't affect it at all. Classes are classes, objects are objects. They're no managed, they're not interfered with, nothing happens to them. They're not special is any way.
Static singletons are static singletons, Java is java.
All you need to be aware of is the classloader layout of your container, and how it relates to your deployed applications and resources. (Classes in one app can't see classes in another app, for example.) Most of the time it's not really important. Sometimes, it is, as things get more complicated.
But for the most part, it's just Java.
Addenda:
A better way to look at this is to simply group your classes up in to blocks of locality.
Let's take a simple web app that uses EJBs.
The web app is deployed in a WAR artifact, and the EJBs can be deployed separately, as individual EJBs in the container, or, more likely, in an EAR. When you package your application in an EAR, you will likely bundle the WAR within the EAR as well. So, in the end the EAR contains your WAR, and your EJBs.
Now during development, in this case, you're going to have classes that have are in one of three categories.
Classes that are relevant solely to the EJBs (for example the Session Beans).
Classes that are relevant solely to the WARs (such as a Servlet class).
Classes that are relevant to both (a database entity perhaps).
So, a simple way to package them is in three jar files. A jar file for your WAR (in fact, this is the WAR, with the classes in WEB-INF/classes), a jar file for your EJBs, and a jar file for the 3rd type, we'll call that a library.
In terms of build dependency, the WAR build depends on the lib, and the EJB build depends on the lib. But neither the WAR nor EJB depend on each other, as they don't share anything directly, only indirectly through the 3rd library jar. The lib jar is stand alone, since it doesn't have any dependency on either the WAR or EJBs. Note, your EJB Session Bean interface classes will go in to the library jar (since both tiers rely upon them).
In your ear, you simply bundle the lib jar, the WAR, and the EJB jar along with a META-INF dir and an application.xml file. The WAR has its own structure, with the WEB-INF and all, the EJB jar has its META-INF and ejb-jar.xml. But of note is the that lib.jar is NOT in the WEB-INF/lib directory, it's in the EAR bundle and thus shared by both the EJBs and the WAR using class loader chicanery that the container is responsible for.
This is important to note. For example, if you have, say, a simple static Singleton in your lib jar, then BOTH the WAR and EJBs will share that Singleton, since they're all part of the same class loader. To use that Singleton, it's just normal Java. Nothing special there.
If the EJB and WAR were deployed separately, they would EACH need there own copy of the lib.jar, and in the case of the Singleton, they would NOT share it, since each module would have it's own class loader.
So, barring some real burning need otherwise, it's easier to bundle everything in to an EAR and treat both the EJB tier and WAR tier as a single, integrated application.
Addenda 2:
People don't much talk about using classes in Java EE development because there's nothing to talk about, they just use them, like in any Java program. You're over thinking this here.
The 3 jar idiom: war, ejb, lib is one I've used over the years because it separates the 3 concerns, and limits dependencies. Client -> lib -> EJB. It also simplifies the build, since clients typically need just the lib jar and java. In the Netbeans IDE, this is trivial to manage. With minor work, it's straightforward in other IDEs or even in ant/maven. It's not a huge burden, but keeps the 3 parts relatively clean.
Dependency and Jar management is the nightmare of any large Java project, and even more so with EJB when you're dealing with the different deployable artifacts. Anything that can help mitigate that is a win, in my book, and truth is, a clean, stand alone lib jar helps a lot, especially of you need to integrate and use that lib with other code. For example, if you later write an external GUI client using Remote EJBs, or even web services, the lib jar is the only dependency that client has. The benefits of this jar far outweigh the minor pain it takes to set up this kind of library.
In the end the lib jar is just a jar like any other jar you'd want to use in your application (like logging or any other popular 3rd party jars).

Categories

Resources