I want to add a listener on java method and I saw the annotation #Interceptors and #AroundInvoke.
I want to use it in a classic java project but all tutorials show me Java EE projects.
Is it possible ?
Interceptor is a DI (Dependency injection) concept based on AOP (aspects oriented programming).
Since Java-ee 6 you have a lightweight DI container named CDI.
You can use CDI in a java-se context if you provide an implementation allowing a standalone deployment like jboss weld :
See Is it possible to use javax.interceptor in a Java SE environment?
Otherwise, you can use spring, which also provides a lightweight DI container with the same kind of features and may be better suited for a java-se context usage.
I don't think so, those are managed by the Java EE container.
An easy way is to create a proxy/wrapper over all instances of your class.
Or use Spring AOP (but you will have to configure Spring) or AspectJ.
Check this out: http://www.javacodegeeks.com/2012/06/simple-introduction-to-aop.html
Reading the doc here: https://docs.oracle.com/javaee/6/tutorial/doc/gkigq.html
Interceptors are used in conjunction with Java EE managed classes to allow developers to invoke interceptor methods on an associated target class, in conjunction with method invocations or lifecycle events.
So I guess the answer to your question is no.
Related
I'm looking for a way to add certain functionality to JAX-RS resources in an OSGI environment. Annotations seem to be a clean way to do this and I've seen it done in the Spring framework (no experience). Annotations such as #Transactional, or (what I wanted to do, requires a permission flag to be set on a user) #Permission(CREATE). However, I'm a bit stuck on how to do this in an OSGI environment.
The normal way(is it?) to go about adding aspects would be to register an aspect service that wraps the original service. If I looked it up correctly, JAX-RS resources are tracked and hooked up to an HttpService. JAX-RS resources do not implement an interface and proxies would need to be dynamically created.
How would I dynamically generate OSGI aspect services/resources that effectively hide the original resource from the JAX-RS tracker that hooks it to the HttpService? I have zero experience with existing AOP frameworks and barely any knowledge of AOP itself.
It is very common in the Java EE and Spring world to use interceptors and define additional behavior based on annotations. There are some solutions in OSGi as well, there is an RFP to support EJB annotations.
However, I have a different opinion. Although this looks cool, it is also magical. See the "Why not annotations, interceptors and other magic?" chapter of this README file where I wrote down my reasons. This project implements the logic that you would like to achieve with #Transactional annotation, but it only uses functional interfaces.
I think it is better to think in lambda expressions to achieve the goal you want (see the java 8 example behind the link). If it is not Java 8, you can still use anonymous classes (see jave 7 and above example behind the link). Your code will look more ugly with anonymous classes, but it will be very clear, what your code does.
Others might not like my answer. Three years ago I was one of the biggest fan of annotation scanning, weaving and interceptors. After a couple of headaches, I became an enemy of this "magical" concept.
I want to use Hibernate Validator's method parameter validation feature. From what I read in the documents, Hibernate Validator just offers an API, and I need the #AutoValidating annotation of Seam Validation to make things work.
However, I want to use the methd parameter validation outside a Java EE container, for plain methods, e.g. in utility classes.
What's the setup to get this to work?
For using method validation you need some sort of container creating and managing your objects, it doesn't neccessarily have to be Java EE, though.
If you are running in Java SE, you could e.g. use CDI and Seam Validation (the CDI reference implementation Weld can be used on SE) or alternatively the Spring framework, this post gives a good overview.
On GitHub you can also find a project of mine, showing the integration of method validation with Google Guice and also JDK dynamic proxies.
It is possible to build a Seam-based application living outside of a full-fledged Java EE container, for instance using a web container such as Tomcat. But anyway, Seam has to run in at least a web container, you can't use it outside for standalone applications (after all, Seam is a web applications framework). If you only need validations, consider using a simpler approach - for instance, try Apache's commons validator.
First some background:
I'm working on some webapp prototype code based on Apache Sling which is OSGI based and runs on Apache Felix. I'm still relatively new to OSGI even though I think I've grasped most concepts by now. However, what puzzles me is that I haven't been able to find a "full" dependency injection (DI) framework. I've successfully employed rudimentary DI using Declarative Services (DS). But my understanding is that DS are used to reference -- how do I put this? -- OSGI registered services and components together. And for that it works fine, but I personally use DI frameworks like Guice to wire entire object graphs together and put objects on the correct scopes (think #RequestScoped or #SessionScoped for example). However, none of the OSGI specific frameworks I've looked at, seem to support this concept.
I've started reading about OSGI blueprints and iPOJO but these frameworks seem to be more concerned with wiring OSGI services together than with providing a full DI solution. I have to admit that I haven't done any samples yet, so my impression could be incorrect.
Being an extension to Guice, I've experimented with Peaberry, however I found documentation very hard to find, and while I got basic DI working, a lot of guice-servlet's advanced functionality (automatic injection into filters, servlets, etc) didn't work at all.
So, my questions are the following:
How do declarative services compare to "traditional" DI like Guice or Spring? Do they solve the same problem or are they geared towards different problems?
All OSGI specific solutions I've seen so far lack the concept of scopes for DI. For example, Guice + guice-servlet has request scoped dependencies which makes writing web applications really clean and easy. Did I just miss that in the docs or are these concerns not covered by any of these frameworks?
Are JSR 330 and OSGI based DI two different worlds? iPOJO for example brings its own annotations and Felix SCR Annotations seem to be an entirely different world.
Does anybody have experience with building OSGI based systems and DI? Maybe even some sample code on github?
Does anybody use different technologies like Guice and iPOJO together or is that just a crazy idea?
Sorry for the rather long question.
Any feedback is greatly appreciated.
Updates
Scoped injection: scoped injection is a useful mechanism to have objects from a specific lifecycle automatically injected. Think for example, some of your code relies on a Hibernate session object that is created as part of a servlet filter. By marking a dependency the container will automatically rebuild the object graph. Maybe there's just different approaches to that?
JSR 330 vs DS: from all your excellent answers I see that these are a two different things. That poses the question, how to deal with third party libraries and frameworks that use JSR 330 annotations when used in an OSGI context? What's a good approach? Running a JSR 330 container within the Bundle?
I appreciate all your answers, you've been very helpful!
Overall approach
The simplest way to have dependency injection with Apache Sling, and the one used throughout the codebase, is to use the maven-scr-plugin .
You can annotate your java classes and then at build time invoke the SCR plugin, either as a Maven plugin, or as an Ant task.
For instance, to register a servlet you could do the following:
#Component // signal that it's OSGI-managed
#Service(Servlet.class) // register as a Servlet service
public class SampleServlet implements Servlet {
#Reference SlingRepository repository; // get a reference to the repository
}
Specific answers
How do declarative services compare to "traditional" DI like Guice or Spring? Do they solve the same problem or are they geared towards different problems?
They solve the same problem - dependency injection. However (see below) they are also built to take into account dynamic systems where services can appear or disappear at any time.
All OSGI specific solutions I've seen so far lack the concept of scopes for DI. For example, Guice + guice-servlet has request scoped dependencies which makes writing web applications really clean and easy. Did I just miss that in the docs or are these concerns not covered by any of these frameworks?
I haven't seen any approach in the SCR world to add session-scoped or request-scoped services. However, SCR is a generic approach, and scoping can be handled at a more specific layer.
Since you're using Sling I think that there will be little need for session-scoped or request-scoped bindings since Sling has builtin objects for each request which are appropriately created for the current user.
One good example is the JCR session. It is automatically constructed with correct privileges and it is in practice a request-scoped DAO. The same goes for the Sling resourceResolver.
If you find yourself needing per-user work the simplest approach is to have services which receive a JCR Session or a Sling ResourceResolver and use those to perform the work you need. The results will be automatically adjusted for the privileges of the current user without any extra effort.
Are JSR 330 and OSGI based DI two different worlds? iPOJO for example brings its own annotations and Felix SCR Annotations seem to be an entirely different world.
Yes, they're different. You should keep in mind that although Spring and Guice are more mainstream, OSGi services are more complex and support more use cases. In OSGi bundles ( and implicitly services ) are free come and go at any time.
This means that when you have a component which depends on a service which just became unavailable your component is deactivated. Or when you receive a list of components ( for instance, Servlet implementations ) and one of them is deactivated, you are notified by that. To my knowledge, neither Spring nor Guice support this as their wirings are static.
That's a great deal of flexibility which OSGi gives you.
Does anybody have experience with building OSGI based systems and DI? Maybe even some sample code on github?
There's a large number of samples in the Sling Samples SVN repository . You should find most of what you need there.
Does anybody use different technologies like Guice and iPOJO together or is that just a crazy idea?
If you have frameworks which are configured with JSR 330 annotations it does make sense to configure them at runtime using Guice or Spring or whatever works for you. However, as Neil Bartlett has pointed out, this will not work cross-bundles.
I'd just like to add a little more information to Robert's excellent answer, particularly with regard to JSR330 and DS.
Declarative Services, Blueprint, iPOJO and the other OSGi "component models" are primarily intended for injecting OSGi services. These are slightly harder to handle than regular dependencies because they can come and go at any time, including in response to external events (e.g. network disconnected) or user actions (e.g. bundle removed). Therefore all these component models provide an additional lifecycle layer over pure dependency injection frameworks.
This is the main reason why the DS annotations are different from the JSR330 ones... the JSR330 ones don't provide enough semantics to deal with lifecycle. For example they say nothing about:
When should the dependency be injected?
What should we do when the dependency is not currently available (i.e., is it optional or mandatory)?
What should we do when a service we are using goes away?
Can we dynamically switch from one instance of a service to another?
etc...
Unfortunately because the component models are primarily focused on services -- that is, the linkages between bundles -- they are comparatively spartan with regard to wiring up dependencies inside the bundle (although Blueprint does offer some support for this).
There should be no problem using an existing DI framework for wiring up dependencies inside the bundle. For example I had a customer that used Guice to wire up the internal pieces of some Declarative Services components. However I tend to question the value of doing this, because if you need DI inside your bundle it suggests that your bundle may be too big and incoherent.
Note that it is very important NOT to use a traditional DI framework to wire up components between bundles. If the DI framework needs to access a class from another bundle then that other bundle must expose its implementation details, which breaks the encapsulation that we seek in OSGi.
I have some experience in building applications using Aries Blueprint. It has some very nice features regarding OSGi services and config admin support.
If you search for some great examples have a look at the code of Apache Karaf which uses blueprint for all of its wiring.
See http://svn.apache.org/repos/asf/karaf/
I also have some tutortials for Blueprint and Apache Karaf on my website:
http://www.liquid-reality.de/display/liquid/Karaf+Tutorials
In your environment with the embedded felix it will be a bit different as you do not have the management features of Karaf but you simply need to install the same bundles and it should work nicely.
I can recommend Bnd and if you use Eclipse IDE sepcially Bndtools as well. With that you can avoid describing DS in XML and use annotations instead. There is a special Reference annotation for DI. This one has also a filter where you can reference only a special subset of services.
I am using osgi and DI for current my project, I've choosed gemini blueprint because it is second version of SPRING DYNAMIC MODULES, Based on this information I suggest you to read Spring Dynamic Modules in Action. This book will help you to understand some parts and points how to build architecture and why is it good :)
Running into a similar architecture problem here - as Robert mentioned above in his answer:
If you find yourself needing per-user work the simplest approach is to
have services which receive a JCR Session or a Sling ResourceResolver
and use those to perform the work you need. The results will be
automatically adjusted for the privileges of the current user without
any extra effort.
Extrapolating from this (and what I am currently coding), one approach would be to add #param resourceResolver to any #Service methods so that you can pass the appropriately request-scoped object to be used down the execution chain.
Specifically we've got a XXXXService / XXXXDao layer, called from XXXXServlet / XXXXViewHelper / JSP equivalents. So managing all of these components via the OSGI #Service annotations, we can easily wire up the entire stack.
The downside here is that you need to litter your interface design with ResourceResolver or Sessions params.
Originally we tried to inject ResourceResolverFactory into the DAO layer, so that we could easily access the session at will via the factory. However, we are interacting with the session at multiple points in the hierarchy, and multiple times per request. This resulted in session-closed exceptions.
Is there a way to get at that per-request ResourceResolver reliably without having to pass it into every service method?
With request-scoped injection on the Service layers, you could instead just pass the ResourceResolver as a constructor arg & use an instance variable instead. Of course the downside here is you'd have to think about request-scope vs. prototype-scope service code and separate out accordingly.
This seems like it would be a common problem where you want to separate out concerns into service/dao code, leaving the JCR interactions in the DAO, analogous to Hibernate how can you easily get at the per-request Session to perform repo operataions?
I was made aware with the annotation base configuration (the #Resource) feature in Java EE which I really like. Then I noticed that the annotation was actually part of Java SE.
So I wonder if I can use it with Java SE. I can surely use the annotation in a standalone program but I am find how to actually configure it. All the examples I found involve creating a Java EE configuration file. Can any one give me a confirmation (or give me a reference to one) that it can be used outside of Java EE environment? and how to do that?
Annotations have specific purposes and can only be used for those purposes. So Java EE annotations will in most cases have no function outside Java EE. But for instance jUnit and JPA annotations should work in a Java SE applications. You can also roll your own if you feel like it.
I'm thinking the same thing. Something must process annotations--this is what Spring does, but currently I'm not using Spring.
It wouldn't be too difficult to add custom annotation processing to handle the #Resource, #PostConstruct and #PreDestroy annotations (It would probably be a few dozen lines of code) but at some point you gotta think "Well, Spring is already doing all that and a heck of a lot more".
They are also implemented by Tomcat for WebServices, so you can just use them but only on properly configured #WebService classes.
Does someone can tell me what's new in Spring 3 and the difference to two (Spring 2.5 and Spring 3)?
See here whats new in Spring 3.0.
Here are some excerpts from the page New Features and Enhancements in Spring 3.0 with links to the relevant technologies:
Java 5
The entire framework code has been revised to take advantage of Java 5
features like generics, varargs and other language
improvements. We have done our best to still keep the code backwards
compatible. We now have consistent use of generic Collections and
Maps, consistent use of generic FactoryBeans, and also
consistent resolution of bridge methods in the Spring AOP API.
Generic ApplicationListeners automatically receive specific event
types only. All callback interfaces such as TransactionCallback
and HibernateCallback declare a generic result value now.
Overall, the Spring core codebase is now freshly revised and optimized
for Java 5.
Spring's TaskExecutor abstraction has been updated for close
integration with Java 5's java.util.concurrent facilities. We
provide first-class support for Callables and Futures now,
as well as ExecutorService adapters, ThreadFactory
integration, etc. This has been aligned with JSR-236
(Concurrency Utilities for Java EE 6) as far as possible. Furthermore,
we provide support for asynchronous method invocations through the use
of the new #Async annotation (or EJB 3.1's #Asynchronous
annotation).
Overview of new features
This is a list of new features for Spring 3.0. We will cover these
features in more detail later in this section.
Spring Expression Language
IoC enhancements/Java based bean metadata
General-purpose type conversion system and field formatting
system
Object to XML mapping functionality (OXM) moved from Spring
Web Services project
Comprehensive REST support
#MVC additions
Declarative model validation
Early support for Java EE 6
Embedded database support
Check this http://www.infoq.com/presentations/Whats-New-in-Spring-3.0