Java annoations - java

I used a lot annotations in java but I never wrote one. I read though several guides and I am really confused.
They are using annotations like meta information eg names, age etc. That is really confusing because I want to do something different
http://www.developer.com/java/other/article.php/3556176/An-Introduction-to-Java-Annotations.htm
I want to control the function calls.
for example
#Permission(user)
public static void account(){
...
}
So my functions only gets called if the user has the permission, otherwise the user should be redirected to the login page.
I could not find any information, maybe I am using the wrong keyword?
I hope you can clear things up,
Thanks.

You can do that, but with a lot of extra code. Intercepting method calls is part of AOP (aspect oriented programming). You need to make proxies of you target objects, and in the invocation handler parse the annotation.
Luckily, you don't have to do that - since you have a webapp, just use spring/spring-mvc/spring-security. Spring gives you an AOP framework that you can use to define aspects handling your permission logic

Not sure how you can do this by yourself but if you are using Spring they have something that may help
http://static.springsource.org/spring-security/site/docs/3.0.7.RELEASE/reference/el-access.html
I use it my current project and it works well

Something like that should really be done in the function itself (or in some other part of the program). Note that annotations provide data about a program that is not part of the program itself (see this reference).

I think what you are after is an AOP advisor which is run before your method. See here: http://java-questions.com/spring_aop.html
As an alternative to Spring, you could use AspectJ: http://www.andrewewhite.net/wordpress/2010/03/17/aspectj-annotation-tutorial/

Related

Details on how front end interacts with back end?

Consider this line of jsp code:
function clearCart(){
cartForm.action="cart_clear?method=clear";
cartForm.submit();
}
Clearly it's trying to call a method on the back end to clear the cart. My question is how does the service (Tomcat most likely, correct me if I'm wrong) which hosts this site that contains this snippet of code know how and where to find this method, how it "indexes" it with string values etc. In my java file, the clear method is defined as:
public String clear( )
{
this.request = ServletActionContext.getRequest();
this.session = this.request.getSession();
logger.info("Cart is clearing...");
Cart cart = ( Cart ) this.session.getAttribute(Constants.SESSION_CART );
cart.clear();
for( Long id : cart.getCartItems().keySet() )
{
Item it = cart.getCartItems().get(id);
System.out.println( it.getProduct().getName() + " " + it.getNumber()
);
}
return "cart";
}
By which module/what mechanism does Tomcat know how to locate precisely that method? By copycatting online tutorials and textbooks I know how to write these codes, but I want to get a bit closer to the bottom of it all, or at least something very basic.
Here's my educated (or not so much) guess: Since I'm basing my entire project on struts, hibernate and spring, I've inadvertently/invariably configured the build path and dependencies in such ways that when I hit the "compile" button, all the "associating" and "navigating" are done by these framework, in other words, as long as I correctly configured the project and got spring etc. "involved" (sorry I can't think of that technical jargon that's on the tip of my tongue), and as long as I inherit a class or implement an interface, when compiling, the compiler will expose these java methods to the jsp script - it's part the work done by compiler, part the work done by the people who composed spring framework. Or, using a really bad analogy, consider a C++ project whereby you use a 3rd party library which came in compiled binary form, all you have to do is to do the right inclusion (.h/.hpp file) and call the right function and you'll get the function during run time when calling those functions - note that this really is a really bad analogy.
Is that how it is done or am I overthinking it? For example it's all handled by Tomcat?
Sorry for all the verbosity. Things get lengthy when you need to express slightly more complicated and nuanced ideas. Also - please go deep and go low-level don't go too deep, by that I mean you are free to lecture on how hibernate and spring etc. work, how its code is being run on a server, but try not to touch the java virtue machine, byte code and C++ pointers etc. unless of course, it is helpful.
Thanks in advance!
Tomcat doesn't do much except obey the Servlet specification. Spring tells Tomcat that all requests to http://myserver.com/ should be directed to Spring's DispatcherServlet, which is the main entry point.
Then it's up to Spring to further direct those requests to the code that handles them. There are different strategies for mapping a specific URL to the code that handles the request, but it's not set in stone and you could easily create your own strategy that would allow you to use whatever kind of URLs you want. For a simple (and stupid) example you could have http://myserver.com/1 that would execute the first method in a single massive handler class, http://myserver.com/2 would execute the second, etc.
The example is with Spring, but it's the same general idea with other frameworks. You have a mapper that maps an URL to the handler code.
These days it's all hidden under layers of abstraction so you don't have to care about the specifics of the mapping and can develop quickly and concentrate on the business code.

Trying to implement answer (SO) about AOP spring to logging in REST API - some doubts

Firstly I tell that I am newbie at spring (on the whole, also AOP). At this moment I have working rest api.
I am trying to use this thread:
Spring Boot - How to log all requests and responses with exceptions in single place?
I am using spring boot and only annotations configuration. I tried to follow this tutorial, however I have simple problems, I ask you for your help ( I tried to read more about AOP, but I would rather implement concrete example and then try to dig deeper ).
1. <aop:aspectj-autoproxy/> Is it possible to express it using only annotations ?
2.
#Retention(RetentionPolicy.RUNTIME)
#Target({ElementType.METHOD,ElementType.TYPE})
public #interface EnableLogging {
ActionType actionType();
}
Where this fragment should resiude ? I tried to conclude and some place, but no effect.
3. What about turning on Aspect ? What does it mean ? For example, what does it mean this line:
#AfterReturning(pointcut = "execution(#co.xyz.aspect.EnableLogging * *(..)) && #annotation(enableLogging) && args(reqArg, reqArg1,..)", returning = "result")
Thanks in advance, answers to this question should help me get better aop.
Haskell, why don't you ask your question in a comment under the answer you are referring to instead of in a new question? Anyway, as for your questions:
Yes, you can replace <aop:aspectj-autoproxy/> by #EnableAspectJAutoProxy, see Spring AOP manual, chapter 11.2.1.
This "fragment" is not a fragment but a full Java annotation declaration. Maybe you want to learn some Java basics before trying complicated stuff like Spring AOP?
Please read the full Spring AOP chapter in order to get a basic understanding of Spring AOP. As for the AspectJ language as such or the meaning of terms such as joinpoint, pointcut, advice, you should read an AspectJ primer. This code snippet expresses the following:
#AfterReturning: The advice method should always run after an intercepted method specified by the following pointcut has returned without an exception.
pointcut: an expression describing where to weave in the subsequent advice code into your original code.
execution(#co.xyz.aspect.EnableLogging * *(..)): whenever a method annotated by #EnableLogging is executed, no matter how many and which types of parameters and not matter which return type it has.
#annotation(enableLogging) binds the method annotation to an advice parameter so you can easily access it from the advice.
args(reqArg, reqArg1,..) binds the first two parameters of the intercepted method to advice parameters so you can easily access those, too.
returning = "result" binds the intercepted method's return value to another advice parameter so you can easily access that one from the advice as well.

How should I write my own custom Annotation in Java

Let say I want to check condition[let say boundary values] on some of the method arguments.Instead of writing "if" condition to check [boundary condition] on every method, I want to annotate argument only. Let me know the Steps to understand it. Working code will be awesome.
You need to look into method interception. What you are wanting is an interceptor that can validate method arguments on invocation. I like the AOP Alliance interfaces for this, they work pretty well. It also integrates with Guice natively and I think Spring has support for it as well.
Steps:
Define an annotation
Create an interceptor to process the annotation
Bind the interceptor (manually or using some framework)

How best to implement save() and setDirty() for my Java beans model?

I have a Java model which is effectively a tree of Java beans. Different areas of my application can change different beans of the model. When finished, I want to save the model, which should be able to work out which beans have actually changed, and call there
I know I can implement save(), isDirty() and setDirty() methods in all the beans, and have the setter check whether there is a change and call setDirty(). But ideally I don't want to have to programmicatically do this for each setter. I want to just be able to add new properties to the beans with no additional coding.
I'm also aware of PropertyChangeListeners, but again I would have to programmatically fire a change in each setter.
Can anyone recommend a pattern/aspect/annotation that I might be able to use to make my life easier? I don't think what I'm trying to achieve is everything new or groundbreaking so hoping there's something out there I can use.
Note that I'm coding in basic Java, so no fancy frameworks to fall back on (expect Spring for bean management - outside of my model).
Thanks in advance.

Do you use Java annotations? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
How and where are Annotations used in Java?
Java beans, annotations: What do they do? How do they help me?
Over and over, I read about Java 5's annotations being an 'advanced feature' of the language. Until recently, I haven't much used annotations (other than the usual #Override, &c), but work on a number of webservice-related projects has forced my hand. Since I learned Java pre-5, I never really took the time to sit down and grok the annotation system.
My question- do you guys actually use annotations? How helpful are they to you, day-to-day? How many StackOverflow-ers have had to write a custom annotation?
Perhaps the most useful and used case of Java Annotations is to use POJO + Annotation instead of xml configuration files
I use it a lot since (as you already stated) if you use a web framework (like spring or seam) they usually have plenty of annotations to help you.
I have recently wrote some annotations to build a custom statemachine, validations purpose and annotations of annotations (using the metadata aspect of it). And IMO they help a lot making the code cleaner, easier to understand and manage.
Current project (200KLOC), annotations I use all the time are:
#NotNull / #Nullabe
#Override
#Test
#Ignore
#ThreadSafe
#Immutable
But I haven't written yet my own annotation... Yet!
I have used annotations for:
Hibernate, so I don't need to keep those huge XML files;
XML Serialization, so I describe how the object should be rendered in the object itself;
Warning removal for warnings that I don't want to disable (and for which the particular case cannot be properly solved).
I have created annotations for:
Describe the state required in order for my method to be executed (for example, that a user must be logged in);
Mark my method as executable from a specific platform with additional properties for that platform;
And probably some other similar operations.
The annotations that I have created are read with Reflection when I need to get more information about the object I am working with. It works and it works great.
Annotations are just for frameworks and they do work great in hibernate/jpa. until you write a framework that needs some extra information from passed to it objects you wont write your own annotations.
however there is new and cool junit feature that let you write your own annotations in tests - http://blog.mycila.com/2009/11/writing-your-own-junit-extensions-using.html
I use annotations daily and they are wonderful. I use them with jsf and jpa and find them much easier to manage and work with than the alternative XML configurations.
I use annotations for describing in my state synchronisation system what classes are specialisations of the annotated classes, and the environment in which they should be used (when an object is created, it will work out for its entity lists which are the best entity classes to create for the nodes on the network; i.e., a Player entity for a server node is instead a ServerPlayer entity). Additionally, the attributes inside the classes are described and how they should be synchronised across machines.
We just used annotations to create a simple way to validate our POJO's:
#NotEmpty
#Pattern(regex = "I")
private String value;
Then we run this through the Hibernate validator which will do all our validation for us:
import org.hibernate.validator.ClassValidator;
import org.hibernate.validator.InvalidValue;
public void validate(T validateMe) {
ClassValidator<T> validator = new ClassValidator<T>((Class<T>) validateMe.getClass());
InvalidValue[] errors = validator.getInvalidValues(validateMe);
}
Works great. Nice clean code.
We use custom annotations as a part of our integration testing system:
#Artifact: Associates an integration test with an issue ID. Trace matrices are then automatically generated for our testing and regulatory departments.
#Exclude: Ignores an integration test based on the browser platform / version. Keeps the IE 6 bugs from clogging up our nightly test runs :)
#SeleniumSession: Defines test specific selenium settings for each integration test.
They are a very powerful tool, but you gotta use them carefully. Just have a look at those early .NET Enterprise class files to see what a nightmare mandatory annotations can be :)
We have a report builder as part of our webapp. A user can add a large number of widgets that are all small variations on the same set of themes (graphs, tables, etc).
The UI builds itself based on custom annotations in the widget classes. (e.g. an annotation might contain default value and valid values that would render as a dropdown. Or a flag indicating if the field is mandatory).
It has turned out be be a good way to allow devs to crank out widgets without having to touch the UI.

Categories

Resources