Java annotation and code execution at runtime - java

Annotations supposedly are markers/provide metadata, so for example how does the #RolesAllowed annotation in JAX-RS work? This annotation "executes" code since it checks that the user is authenticated and has the required roles, at runtime (when an annotated method is called).

No. There is code that checks if the annotation exists and performs operations based on it. The annotation itself just lies there. The code that performs the checking and operations is executed around the method call.

Related

Design a custom annotation to invoke a method in a jar

I'm a bit new to annotations in Java. Is it possible to design a custom annotation which when used in a class automatically invokes a method present inside another Class. TIA.
The answer is "sort of": annotations by themselves do nothing (except "compile time" annotations that affect the compile process).
Meaning: just attaching an annotation to something doesn't magically cause a method to be called at some arbitrary point in time.
This works differently: you have some sort of framework - and at some point you ask the framework to process an object, class, ... And then the framework might check for the presence of certain annotations to "do" something based on that check.
Thus: it is possible to implement custom annotations, and it is also possible to make some "framework" react to the presence of that annotation.
In case you find this answer too generic - well, it can't be more precise/specific than the question ...

Java annotation that disregards method call if a condition is not satisfied

Is there a way in Java to make an annotation you put before a method to check if a boolean or any variable is defined/a-certain-value and if it's not it disregards the call to the method (no code from the method will be executed)?
Annotations just provide metadata about your code. They cannot directly influence your code without the use of tools such as JUnit. As stated here:
Annotations, a form of metadata, provide data about a program that is not part of the program itself. Annotations have no direct effect on the operation of the code they annotate.

validate() method after validation.xml

I have a -validation.xml file to check if the fields of the form are empty and that kind of simple validation. I also have a validate() method (extended from ActionSupport) to check more complicated things. But when I send the form it checks the method before the XML file, so if the fields are empty a NullPointerException appears. At least that's what I think is happening.
So my question is, is there a way to change the order of the validation, so the XML is checked before the method?
EDIT: I had the idea of checking if the String is not null in the validate() method so I can avoid the problem, but I don't think that's the wisest thing to do.
The interceptor does check XML first, but IIRC doesn't stop validation if it find errors. I believe I have a patch for this, controlled with a flag.
I've solved this before by checking for errors in the validate method and not proceeding if errors existed.
The order is always one, that is hardcoded order.
The process of validation is performed by the ValidationInterceptor class (at least version 2.3.8).
This interceptor runs the action through the standard validation framework, which in turn checks the action against any validation rules (found in files such as ActionClass-validation.xml) and adds field-level and action-level error messages (provided that the action implements ValidationAware). This interceptor is often one of the last (or second to last) interceptors applied in a stack, as it assumes that all values have already been set on the action.
This interceptor does nothing if the name of the method being invoked is specified in the excludeMethods parameter. excludeMethods accepts a comma-delimited list of method names. For example, requests to foo!input.action and foo!back.action will be skipped by this interceptor if you set the excludeMethods parameter to "input, back".
The workflow of the action request does not change due to this interceptor. Rather, this interceptor is often used in conjunction with the workflow interceptor.
NOTE: As this method extends off MethodFilterInterceptor, it is capable of deciding if it is applicable only to selective methods in the action class. See MethodFilterInterceptor for more info.
First, it checks if the declarative validation is enabled and do it, then it checks if programmatic validation is enabled and do it.
You can turn on/off each type of validation via the interceptor parameters.
Interceptor parameters:
alwaysInvokeValidate - Defaults to true. If true validate() method will always be invoked, otherwise it will not.
programmatic - Defaults to true. If true and the action is Validateable call validate(), and any method that starts with "validate".
declarative - Defaults to true. Perform validation based on xml or annotations.

Apache Wink resource lifecycle

I'd like to know what the expected lifecycle behavior is for a class that responds to REST requests.
I have a class that's derived from javax.ws.rs.core.Application that identifies another class for responding to requests.
In that other class, it is annotated with #Path("foo") and methods within this class are annotated with #Path("bar"). When a request is made to foo/bar, I can see that the constructor is executed, then the PostConstruct method is properly called. After the method returns a response to the client, I can see that PreDestroy is called and then the class is squashed. On the next request, the process repeats.
Is this the correct behavior? Or is there a way that this class can remain in memory so that it doesn't need to go through the constructor and PostConstruct each time a request is made? This method relies on JAXB marshalling and various XSL transformations - I would like to cache the compiled XSLT transformation objects as well as the results of some transformations, but if the class is reinstantiated each time it is called, it makes it impossible for local caching.
This is running with Java 7, Wink, and Tomcat 7. Can someone please let me know if this is the expected behavior, or am I missing something that will just keep this class alive?
Thanks.
By JAX-RS specification, the Resources (the classes annotated with #Path) are created per request.
There are several ways to override this behavior.
The simplest way that can be used according to the JAX-RS specification, is to create a resource instance yourself (you are responsible to call the PostConstruct, not sure when and how you call to PostDestroy in this case) and return it using javax.ws.rs.core.Application.getSingletons()
Alternately, you can put #org.apache.wink.common.annotations.Scope(ScopeType.SINGLETON) annotation on your resource.
If you use Spring, Wink has a neat Spring integration module, so the Spring's lifecycle will be used. See http://incubator.apache.org/wink/1.0/html/5.5%20Spring%20Integration.html

Check if the method is invoked

I am trying to create a logging OSGi bundle, which would be able to log input, output, exception (if any) parameters of all the methods which are marked with specific annotation.
I have tried to set up the Spring AOP logging in OSGi but I was unsuccessful.
All I need to know is how to determine when the method is being called? For example I have scanned all methods in a class which are annotated with my annotation and I have those methods in array or list.
For example there are three methods: getStatus, getDetails, getSomething. And the user invokes getDetails method, so how should I know when this method is invoked?
Detecting method calls requires you to instrument your code. If you want to do this at runtime this requires byte-code manipulation (which is what Spring AOP does, as far as I know). Alternatively you could instrument your code at compile-time using a custom preprocessing step that generates the instrumented Java-code, but I don't know if that is much easier.
I guess your best bet is to try and Spring AOP working.

Categories

Resources