I am trying to have an annotation #FeatureDependent be used on methods to signal that the method requires certain things to be enabled in order for it to work. And I was wondering if it was possible to have a method called everytime a method with #FeatureDependent was called which would check if the criteria were met for the method to be called.
It sounds like you are describing Aspect Oriented Programming (AOI). This technique allows you to address "cross-cutting" concerns, tasks like logging, security, and transaction management which tend to affect many methods in the same manner. Your use case sounds like it would be a good fit for AOP.
There are two common approaches to AOP. The first mechanism is to create objects in a container (e.g. a Spring container). The container can then scan the class, detect any advice that needs to be applied, and apply the advice via dynamic proxies (Googling Spring and AOP is a good place to start with this). The downside is that your components will need to be constructed by a container so it makes sense for larger components.
The second approach is an extra compilation step (sometimes done at compilation, sometimes done as a separate compilation phase, and sometimes done by a weaving class loader) to wire in the additional methods. This is typically called "weaving" and AspectJ is a common library to look into for this.
Both approaches will allow you to apply "advice" (code run before and after a method invocation) based on annotations on an object. Explaining either in more detail would be beyond the scope of a SO answer but I hope it can get you started.
I should warn that AOP has gotten a bit of a reputation for complicating the flow of an application and tending to be difficult to understand and debug. As a result it has declined in popularity lately.
Another approach is to use something like Servlet Filters, basically a single choke point for all requests and workflows where you can apply various logging & security mechanisms. Such an approach tends to be a little easier to understand and involve a bit less "black magic".
Related
I have a component declared using the #Component annotation, in which there is a set of methods that implement communication with another api, in my product there are operations that are prohibited for a user with an anonymous id. I want to create an annotation, for example #ProhibitedForAnonym, which, every time the method is called, will check the ID of the anonymous customer, with the ID in the method parameter and throw an error if the IDs match. But I don't understand how to do annotation processing in OSGI, maybe some kind of interceptor?
There is no general interception framework in OSGi. However, you could do interception in the following ways:
Don't. Personally, I feel that since we've lambdas a code-based solution has won hands on over a 'magic' annotation check. It is about the same number of characters but a lambda based call allows me to single step, provide context to the security check, does not suffer from the THIS problem, is testable, and requires no complex framework with lots of bug opportunities.
Use the byte code weaving support in OSGi. You need to register a weaver early and then weave any class that has these annotations. You can take a look at https://github.com/aQute-os/biz.aQute.osgi.util/tree/master/biz.aQute.trace for an example of how to use the byte code weaver. Make sure your weaver is there first. If you use bndtools you can add it to the -runpath to run before anybody else. Or use start levels.
Use proxying. You can 'hide' and original service with the Service Hooks and then register a proxy. In the proxy you can then do the annotation check. This also requires that this code runs first and cannot be updated. I think the spec has an example of this
You might want to read: https://www.aqute.biz/appnotes/interceptors.html
I know by default JAX-RS endpoints lifecycle is once-per-request, so that the request specific informations can be injected into the instance.
And we can also make an endpoints Singleton meaning once-per-application, in which the request specific informations cannot be injected into the instance rather it can be injected into the requested method.
1. So i would like to know which approach is better in terms of performance, either once-per-request or once-per-application.
2. I would also like to know the pros and cons of these approaches other the injecting request specific informations
3. Which approach you prefer to use in your API applications
Note: i have been using the once-per-request approach so far, but i always wonder is that is efficient, definitely its make coding easier and reusable.
To start with your last question: I'm always using the default (per-request) and I seldom came to a point where I wanted to change this.
What might be a reason to prefer one over the other?
If you want to serve some static content (maybe a welcome-document of your API) it makes sense to produce this content only once and hold it in a singleton resource class. But you can achieve the same by e.g. injecting an #ApplicationScoped CDI bean in a per-request scoped resource class.
If you prefer injecting the #xxxParam values like #QueryParam as fields instead of method parameters you should use the per-request lifecycle. This is not supported for singletons. (This does not include injecting via #Context).
I made a little test to compare the performance of both. You can find the sources and the results on github. In short: I measured a difference from about 1.5 %. I don't think this should affect your application too much.
Comparing the results of the JVisualVM monitoring I would tend to say that the per-request test is using more memory but you should decide on your own if this really affects your application.
I am new to spring and learning Spring aop. Two advantages of AOP are :
Eliminate code scattering
To avoid code tangling
The first one makes sense to me because of duplication of same code being used in many classes and by using an aspect we can avoid duplicating OF the code in many classes instead define a point cut that will determine where the code will be implemented.
However how do we avoid code tangling in spring?I am not able to find a simple example to show how aop avoid code tangling.
Thanks.
"code tangling" means that one code fragment is responsible for more than one requirement.
AOP helps separating them.
For example you have the two requirements:
- Delete a User
- Every action that is done to an user needs to be logged
Now you can use AOP to separate the logging stuff out to an aspect and you will got two single code fragments (the delete function and the logging aspect) that are now responsible only for one requirement.
Code tangling: Modules in a software system may simultaneously interact with several requirements
For example, oftentimes developers simultaneously think about business logic, performance, synchronization, logging, and security. Such a multitude of requirements results in the simultaneous presence of elements from each concern's implementation, resulting in code tangling.
I'm running a server which on occasion has to search what a client queries. I'd like to write the client query to disk for records, but I don't want to slow down the search anymore than I have to. (The search is already the bottleneck...)
So, when the client performs a search, I'm having the client's thread send a message to a singleton thread, which will handle the disk write, while the client thread continues to handle the client's requests. That way, the file on disk doesn't run into sync issues, and it doesn't slow the clients experience down.
I have a conceptual question here: is the singleton appropriate in this case? I've been using the singleton design pattern a little too much in my recent programming, and I want to make sure that I'm using it for its intended use.
Any feedback is greatly appreciated.
The singleton pattern is definitely overused and comes with its share of difficulties (unit-testing is the canonical example), but like everything in design, you need to weigh the pros and cons for your specific scenario. The singleton pattern does have its uses. There are options that may allow you to get the singleton behaviour, while alleviating some of the inherent issues:
Interception (often referred to as aspect oriented programming, though I've seen debate that they are not exactly the same thing... can't find the article I read on this at this time) is definitely an option. You could use any combination of construction injection, the decorator pattern, an abstract factory and an inversion of control container. I'm not up on my Java IoC containers, but there are some .Net containers that allow automatic interception (I believe Spring.Net does, so likely Spring (Java) has this built in). This is very handy for any type of cross-cutting concerns, where you need to perform certain types of actions across multiple layers (security, logging etc.). Also, most IoC containers allow you to control lifetime management, so you would be able to treat your logger as a singleton, without having to actually implement the singleton pattern manually.
To sum it up. If a singleton fits for your scenario (seems plausible from your description), go for it. Just make sure you have weighed the pros and cons. You may want to try a different approach and compare the two.
As you many know when you proxy an object, like when you create a bean with transactional attributes for Spring/EJB or even when you create a partial mock with some frameworks, the proxies object doesn't know that, and internal calls are not redirected, and then not intercepted either...
That's why if you do something like that in Spring:
#Transactionnal
public void doSomething() {
doSomethingInNewTransaction();
doSomethingInNewTransaction();
doSomethingInNewTransaction();
}
#Transactional(propagation = Propagation.REQUIRES_NEW)
public void doSomethingInNewTransaction() {
...
}
When you call doSomething, you expect to have 3 new transactions in addition to the main one, but actually, due to this problem you only get one...
So i wonder how do you do to handle these kind of problems...
I'm actually in a situation where i must handle a complex transactional system, and i don't see any better way than splitting my service into many small services, so that I'm sure to pass through all the proxies...
That bothers me a lot because all the code belongs to the same functional domain and should not be split...
I've found this related question with interesting answers:
Spring - #Transactional - What happens in background?
Rob H says that we can inject the spring proxy inside the service, and call proxy.doSomethingInNewTransaction(); instead.
It's quite easy to do and it works, but i don't really like it...
Yunfeng Hou says this:
So I write my own version of CglibSubclassingInstantiationStrategy and
proxy creator so that it will use CGLIB to generate a real subclass
which delegates call to its super rather than another instance, which
Spring is doing now. So I can freely annotate on any methods(as long
as it is not private), and from wherever I call these methods, they
will be taken care of. Well, I still have price to pay: 1. I must list
all annotations that I want to enable the new CGLIB sub class
creation. 2. I can not annotate on a final method since I am now
generating subclass, so a final method can not be intercepted.
What does he mean by "which spring is doing now"? Does this mean internal transactional calls are now intercepted?
What do you think is better?
Do you split your classes when you need some transactional granularity?
Or do you use some workaround like above? (please share it)
I'll talk about Spring and #Transactional but the advise applies for many other frameworks also.
This is an inherent problem with proxy based aspects. It is discussed in the spring documentation here:
http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/aop.html#aop-understanding-aop-proxies
There are a number of possible solutions.
Refactor your classes to avoid the self-invocation calls that bypass the proxy.
The Spring documentation describes this as "The best approach (the term best is used loosely here)".
Advantages of this approach are its simplicity and that there are no ties to any framework. However, it may not be appropriate for a very transactional heavy code base as you'd end up with many trivially small classes.
Internally in the class get a reference to the proxy.
This can be done by injecting the proxy or with hard coded " AopContext.currentProxy()" call (see Spring docs above.).
This method allows you to avoid splitting the classes but in many ways negates the advantages of using the transactional annotation. My personal opinion is that this is one of those things that is a little ugly but the ugliness is self contained and might be the pragmatic approach if lots of transactions are used.
Switch to using AspectJ
As AspectJ does not use proxies then self-invocation is not a problem
This is a very clean method though - it is at the expense of introducing another framework. I've worked on a large project where AspectJ was introduced for this very reason.
Don't use #Transactional at all
Refactor your code to use manual transaction demarcation - possibly using the decorator pattern.
An option - but one that requires moderate refactoring, introducing additional framework ties and increased complexity - so probably not a preferred option
My Advice
Usually splitting up the code is the best answer and can also be good thing for seperation of concerns also. However, if I had a framework/application that heavily relied on nested transactions I would consider using AspectJ to allow self-invocation.
As always when modelling and designing complex use cases - focus on understandable and maintainable design and code. If you prefer a certain pattern or design but it clashes with the underlying framework, consider if it's worth a complex workaround to shoehorn your design into the framework, or if you should compromise and conform your design to the framework where necessary. Don't fight the framework unless you absolutely have to.
My advice - if you can accomplish your goal with such an easy compromise as to split out into a few extra service classes - do it. It sounds a lot cheaper in terms of time, testing and agony than the alternative. And it sure sounds a lot easier to maintain and less of a headache for the next guy to take over.
I usually make it simple, so I split the code into two objects.
The alternative is to demarcate the new transaction yourself, if you need to keep everything in the same file, using a TransactionTemplate. A few more lines of code, but not more than defining a new bean. And it sometimes makes the point more obvious.