I know this topic may have been discussed here regarding making java annotations that have logic functions and do specific actions based on conditions.
One of the famous examples of course are junit and hibernate.
I have also seen annotations that when you place on an api of a web service controller that it checks the header for authentication token and if the user was not authorized it would return unauthorized and would not even enter this api.
Also i have seen an android library that does most of the normal application logic with annotations: http://androidannotations.org/ .
Now all of the tutorials i have seen in the internet regarding this topic don't give clear examples for how to implement it with least code and i find in the end that extra code is written which conflicts with the main purpose of using annotations with logic which is saving time in writing more code.
Take for example in this reference http://androidannotations.org/
#NoTitle
is equivalent to
requestWindowFeature(Window.FEATURE_NO_TITLE);
in this example they seem just to inject their annotation library , they haven't changed any other thing or added any extra code like for example changing the base class which is activity.
Are things just abstracted too much?
And if so how can i reach this level of abstraction to make something like the android library i mentioned above.
Any design patterns recommended for this?
The example that you mentioned, i.e, http://androidannotations.org/ in fact a good implementation of the annotations.
In your example, the Android runtime must be assigning the values to the properties(objects) during runtime, based on the Annotation specified. Methods also can be picked up for execution based on the annotations specified on them.
Annotations, is a simple but powerful concept in Java. You can simplify the usage of your api to a large extent.
Check this post https://devcompass.com/2016/05/08/java-annotations-converting-java-objects-to-excel-data/ for information on how to create annotations from beginning. Checkout the source code zip file at the end of the page.
Trust me, annotations are very simple to learn and they can make a big difference in the source code implementation.
Related
I'm trying to figure out the best way to have my API documentation be the source of truth and use it to validate the actual Java REST code ideally through integration testing or something of that sort. We're using the contract first or consumer contract type of approach, so we don't want the documentation to be generated from annotated code necessarily and updating every time a developer makes a change.
One thought has been to use Swagger, but I'm not sure how best to make it be used for validating the API. Ideally, it'd be good to have the validation occur in the build or integration testing process to see if the real response (and request if possible) match what's expected. I know there are a lot of uses and tools for Swagger and just trying to wrap my head around it. Or if there is a better alternative to work with Java code.
Recently, we (swagger-codegen community) start adding automatic test case generation to API clients (C#, PHP, Ruby). We've not added that to Java yet. Here are some example test cases generated by Swagger-Codegen for C#:
https://github.com/swagger-api/swagger-codegen/tree/master/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test
It's still very preliminary and we would like to hear feedback from you to see if that's what you're looking for.
I think you should try swagger-request-validator:
https://bitbucket.org/atlassian/swagger-request-validator
Here are some examples how to use it:
https://bitbucket.org/atlassian/swagger-request-validator/src/master/swagger-request-validator-examples/
Another alternative is assertj-swagger:
https://github.com/RobWin/assertj-swagger
You may want to look at Spring Cloud Contract. It offers you a DSL, where you can describe the scenarios (more or less what is the response I get for a given request) and it seems to fit well to what you described as a requirement...
If you're using the Spring Framework, I'd highly recommend checking out Spring RestDocs which allow you to generate
I am new to Spring framework and have seen annotations at many places. I understand Built-in Java Annotations like #Deprecated, #Override, #SuppressWarnings.
I have below questions:
Does one need to understand creating custom annotations to understand Spring framework?
For what purpose annotations are required?
Annotations are used to describe elements and clarify their meaning. Prior to their inclusion, that information had to be kept somewhere else, generally a file.
Also, knowing how a java feature works is always useful. So despite you don't need to know how to create your own annotations, it might give you some insight on the internals.
Have a read here:
How and where are Annotations used in Java?
For the first question: You do not need to know how to write an annotation to use it.
For the second:
Annotations are used for many different reasons:
To execute code during runtime based on annotations (e.g. #Transactional in spring)
To create different code during compile dependeing on the annotation (e.g. #AspectJ)
To evaluate code (e.g. javac or FindBugs)
...
There are many things that could be done with annotations.
You need not know about the custom annotations in order to learn Spring annotations.
For Spring annotations, you may start with this link and then explore as you learn further. It explains the usage/need to each of the Spring annotations to get started with.
While not actually answering your questions (which others already answered), this should give you enough information to comfortably use them.
For annotations to actually be useful, you need code which looks for them and handles them accordingly. The same goes for writing your own custom annotations.
Simplified example with #Transactional should make things clear for you. When you put #Transactional on a bean method, there is some Spring code which scans these beans and methods, and picks up your annotated method. Whenever that method is called (won't go into proxies right now), Spring opens a transaction, executes your method, and closes the transaction. You get all of that just by putting annotation on your method.
So, each annotation comes with code that handles it's wanted behavior.
I came along the Drools fluent API which, as far as I understand, allows Rules to be added/edited/deleted from working memory at runtime.
The documentation mentions it here without going into details:
http://docs.jboss.org/drools/release/5.2.0.Final/droolsjbpm-introduction-docs/html/ch02.html#d0e124
Does anyone have example code on how to use this API?
I am specially interested in adding/changing/deleting rules at runtime.
I think that section was speaking more to the fact that they have a programmatic way to create rules. I was under the impression that the "fluent" part referred the their use of the builder pattern that allowed you to string methods together in the same way a rule would appear.
But yes, you are able to change/edit/delete rules dynamically for a particular KnowledgeBase. An example can be found in their sample integration tests, or consult the KnowledgeBase docs - particularly the addKnowledgePackages(Collection<KnowledgePackage> kpackages) and removeRule(String packageName, String ruleName) functions.
I suppose you can combine the DescrFactory with the rule addition/creation. I'm not really able to find a public API anywhere that will help you with how to use it, and it's in the drools-compiler dependency, so I'm not certain that there will be one published as much of that artifact is meant for drools internal use.
There is also another related S/O discussion about this here.
Hi guys: Is there an open source way to associate java #annotations to functional requirements, or for example, TRAC tickets, etc? I want to do something like this:
I'm thinking along the lines of an eclipse plugin which somehow links up with another FOSS project tracking tool, wiki, or maybe even a CSV file.
A somewhat silly but exemplary illustration of what I desire is below:
#Requirement WalkDogTwiceADay
public void walkTheDog()
{
}
#Requirement WalkDogTwiceADay
public void dogWalkerThread()
{
walkTheDog(); //in the morning.
Thread.sleep(36000000);
walkTheDog(); //at night
}
Annotations are metadata, they simply add information to your code for other tools to use or to be inspected at runtime via reflection.
One thing you can do is write an annotation processor that will generate the necessary artefacts. Those could be configuration files, scripts, code...
Another thing you can do is write some tool that knows how to interpret your annotations and uses reflection to find them and take the appropriate actions. For this you'd need to make sure that the annotation type is set to have runtime retention, as opposed to only source or class.
Perhaps some of the stuff found in the answers to this question might prove of use. If that's the case, go ahead and use it. But writing custom annotation processors or code for handling them is not all that terribly hard. The difficult part is getting to know the Java model API that's used by annotation processors, which is like reflection but at compile time (before you have fully-formed classes).
in a previous life, we did something similar with #requirement ##### annotations, and then had a custom javadoc task that turned the requirement annotations into hyperlinks in the javadocs.
I was going to write an addin for eclipse that turned them into links in the code as well, but never got that far.
I am considering starting a project which is used to generate code in Java using annotations (I won't get into specifics, as it's not really relevant). I am wondering about the validity and usefulness of the project, and something that has struck me is the dependence on the Annontation Processor Tool (apt).
What I'd like to know, as I can't speak from experience, is what are the drawbacks of using annotation processing in Java?
These could be anything, including the likes of:
it is hard to do TDD when writing the processor
it is difficult to include the processing on a build system
processing takes a long time, and it is very difficult to get it to run fast
using the annotations in an IDE requires a plugin for each, to get it to behave the same when reporting errors
These are just examples, not my opinion. I am in the process of researching if any of these are true (including asking this question ;-) )
I am sure there must be drawbacks (for instance, Qi4J specifically list not using pre-processors as an advantage) but I don't have the experience with it to tell what they are.
The ony reasonable alternative to using annotation processing is probably to create plugins for the relevant IDEs to generate the code (it would be something vaguely similar to override/implement methods feature that would generate all the signatures without method bodies). However, that step would have to be repeated each time relevant parts of the code changes, annotation processing would not, as far as I can tell.
In regards to the example given with the invasive amount of annotations, I don't envision the use needing to be anything like that, maybe a handful for any given class. That wouldn't stop it being abused of course.
I created a set of JavaBean annotations to generate property getters/setters, delegation, and interface extraction (edit: removed link; no longer supported)
Testing
Testing them can be quite trying...
I usually approach it by creating a project in eclipse with the test code and building it, then make a copy and turn off annotation processing.
I can then use Eclipse to compare the "active" test project to the "expected" copy of the project.
I don't have too many test cases yet (it's very tedious to generate so many combinations of attributes), but this is helping.
Build System
Using annotations in a build system is actually very easy. Gradle makes this incredibly simple, and using it in eclipse is just a matter of making a plugin specifying the annotation processor extension and turning on annotation processing in projects that want to use it.
I've used annotation processing in a continuous build environment, building the annotations & processor, then using it in the rest of the build. It's really pretty painless.
Processing Time
I haven't found this to be an issue - be careful of what you do in the processors. I generate a lot of code in mine and it runs fine. It's a little slower in ant.
Note that Java6 processors can run a little faster because they are part of the normal compilation process. However, I've had trouble getting them to work properly in a code generation capacity (I think much of the problem is eclipse's support and running multiple-phase compiles). For now, I stick with Java 5.
Error Processing
This is one of the best-thought-through things in the annotation API. The API has a "messenger" object that handles all errors. Each IDE provides an implementation that converts this into appropriate error messages at the right location in the code.
The only eclipse-specific thing I did was to cast the processing environment object so I could check if it was bring run as a build or for editor reconciliation. If editing, I exit. Eventually I'll change this to just do error checking at edit time so it can report errors as you type. Be careful, though -- you need to keep it really fast for use during reconciliation or editing gets sluggish.
Code Generation Gotcha
[added a little more per comments]
The annotation processor specifications state that you are not allowed to modify the class that contains the annotation. I suspect this is to simplify the processing (further rounds do not need to include the annotated classes, preventing infinite update loops as well)
You can generate other classes, however, and they recommend that approach.
I generate a superclass for all of the get/set methods and anything else I need to generate. I also have the processor verify that the annotated class extends the generated class. For example:
#Bean(...)
public class Foo extends FooGen
I generate a class in the same package with the name of the annotated class plus "Gen" and verify that the annotated class is declared to extend it.
I have seen someone use the compiler tree api to modify the annotated class -- this is against spec and I suspect they'll plug that hole at some point so it won't work.
I would recommend generating a superclass.
Overall
I'm really happy using annotation processors. Very well designed, especially looking at IDE/command-line build independence.
For now, I would recommend sticking with the Java5 annotation processors if you're doing code generation - you need to run a separate tool called apt to process them, then do the compilation.
Note that the API for Java 5 and Java 6 annotation processors is different! The Java 6 processing API is better IMHO, but I just haven't had luck with java 6 processors doing what I need yet.
When Java 7 comes out I'll give the new processing approach another shot.
Feel free to email me if you have questions. (scott#javadude.com)
Hope this helps!
I think if annotation processor then definitely use the Java 6 version of the API. That is the one which will be supported in the future. The Java 5 API was still in the in the non official com.sun.xyz namespace.
I think we will see a lot more uses of the annotation processor API in the near future. For example Hibernate is developing a processor for the new JPA 2 query related static meta model functionality. They are also developing a processor for validating Bean Validation annotations. So annotation processing is here to stay.
Tool integration is ok. The latest versions of the mainstream IDEs contain options to configure the annotation processors and integrate them into the build process. The main stream build tools also support annotation processing where maven can still cause some grief.
Testing I find a big problem though. All tests are indirect and somehow verify the end result of the annotation processing. I cannot write any simple unit tests which just assert simple methods working on TypeMirrors or other reflection based classes. The problem is that one cannot instantiate these type of classes outside the processors compilation cycle. I don't think that Sun had really testability in mind when designing the API.
One specific which would be helpful in answering the question would be as opposed to what? Not doing the project, or doing it not using annotations? And if not using annotations, what are the alternatives?
Personally, I find excessive annotations unreadable, and many times too inflexible. Take a look at this for one method on a web service to implement a vendor required WSDL:
#WebMethod(action=QBWSBean.NS+"receiveResponseXML")
#WebResult(name="receiveResponseXML"+result,targetNamespace = QBWSBean.NS)
#TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public int receiveResponseXML(
#WebParam(name = "ticket",targetNamespace = QBWSBean.NS) String ticket,
#WebParam(name = "response",targetNamespace = QBWSBean.NS) String response,
#WebParam(name = "hresult",targetNamespace = QBWSBean.NS) String hresult,
#WebParam(name = "message",targetNamespace = QBWSBean.NS) String message) {
I find that code highly unreadable. An XML configuration alternative isn't necessarily better, though.