• Home
  • About
  • Java Without the Boilerplate – Project Lombok

    July 26th, 2010

    Project Lombok is a very cool little Java library that aims (and succeeds) in removing boilerplate, meaningless, and uninteresting code from your Java objects. The basic idea is to replace things like getters and setters with simple annotations, and then let the Java compiler generate the necessary bytecode in the .class file so that tools such as Eclipse and the Java compiler have no idea what anything unusual happened. Lombok hooks into the compiler to make sure this happens correctly.

    First we’ll cover some Lombok basics and then show how it can be used with the Canoo RIA Suite (ULC) project and and view generators. This includes details on how to mix Lombok annotated objects with JPA annotations, which you might want to glance at before leaving!

    Update: You do not need ULC to work with Lombok. The two are separate projects.

    Lombok in Action
    So let’s see Lombok in action. Consider this Java class that includes a Lombok annotation:

    
    import lombok.Data;
    
    public @Data class Contact {
        private String name;
        private String email;
        private String primaryPhone;
    }
    

    OK, so there is an @Data annotation in there. So what? Well, to javac and tools (like Eclipse) this class has getters and setters for all three fields, an equals and hashcode implementation, and a toString method. Eclipse tools still give you autocomplete the Navigator shows the correct methods. Not only did you not have to write (or generate) the code yourself, but you don’t have to see that code when coming back in maintenance mode. The interesting bits of your class are no longer buried in the noise. Consider what this looks like without lombok:
    
    public @Data class Contact {
        private String name;
        private String email;
        private String primaryPhone;
    
        public String getName() {
            return name;
        }
       
        void setName(String name) {
          this.name = name;
        }
        
        public String getEmail() {
            return email;
        }
       
        void setEmail(String email) {
          this.email = email;
        }
    
        public String getPrimaryPhone() {
            return primaryPhone;
        }
       
        void setPrimaryPhone(String primaryPhone) {
          this.primaryPhone = primaryPhone;
        }
    
        @Override public String toString() {
            return "Contact(" + name + ", " 
                    + email + ", " 
                    + primaryPhone + ")";
        }
         
        @Override public boolean equals(Object o) {
            if (o == this) return true;
            if (o == null) return false;
            if (o.getClass() != this.getClass()) return false;
            Contact other = (Contact) o;
            if (name == null 
                    ? other.name != null 
                    : !name.equals(other.name)) return false;
            if (email == null 
                    ? other.email != null 
                    : !email.equals(other.email)) return false;
            if (primaryPhone == null 
                    ? other.primaryPhone != null 
                    : !primaryPhone.equals(other.primaryPhone)) return false;
            return true;
        }
         
        @Override public int hashCode() {
            final int PRIME = 31;
            int result = 1;
            result = (result*PRIME) + (name == null 
                    ? 0 
                    : name.hashCode());
            result = (result*PRIME) + (email == null 
                    ? 0 
                    : email.hashCode());
            result = (result*PRIME) + (primaryPhone == null 
                    ? 0 
                    : primaryPhone.hashCode());
            return result;
        }
    

    That’s a lot of code for something so simple. It doesn’t even fit in my browser margins without funky line breaks! Sure, IDEs can generate it for you. But what if something interesting is buried in the equals() method? Or perhaps a setter has a side-effect? You can’t easily see this with the reams of boilerplate typical of Java. With lombok, only the essentials are displayed, so the unique parts of the object will stand out to the future reader. And yes, even using @Data you are free to provide your own implementations for any of these methods.

    Richard Gabriel made this observation when comparing old programs (like MacPaint) to “modern” programs writen in langauges like Java:

    I’m always delighted by the light touch and stillness of early programming languages. Not much text; a lot gets done. Old programs read like quite conversations between a well-spoken research worker and a well-studied mechanical colleague, not as a debate with a compiler. Who’d have guessed sophistication brought such noise.

    Now, with Lombok, sophistication is finally taking the noise away, rather than adding to it.

    Just a couple important details before moving on to a Lombok example that uses Canoo’s RIA Suite

  • Lombok is compile time only. It does not need to be deployed with your app
  • Lombok works with javac and Eclipse. IntelliJ IDEA will not ’see’ the added methods
  • lombok.jar contains an installer that configures your eclipse.ini file correctly. Be sure to run “java -jar lombok.jar” after you download it (especially for those on 64 bit Linux like me)
  • Lombok with Canoo RIA Suite
    The point of this was to make sure I could use Lombok on my next RIA Suite(aka ULC) project. It’s looks like I can, and you can too. To prove it, let’s generate a RIA Suite project, add a domain class using Lombok, generate the views, and run the application.

    Prerequisites

  • Install Eclipse for Java EE Developers. Make sure that you have for Java EE developers.
  • Install Canoo RIA Suite. Get your download and evaluation key from our customer portal.
  • Install Lombok. Download it and run “java -jar lombok.jar”.
  • Steps
    Here are the steps we’ll perform to get this thing working:

  • Generate a Project using ULC’s Project Generator in Eclipse
  • Add the lombok Jar to your project
  • Create a domain object called Contact and annotate it with @Data
  • Generate the views using ULC’s generate-beans-view in Eclipse
  • Run the app and behold a default, thin client, CRUD application
  • Generate the Project
    The ULC Application Development Guide contains a 10 page getting started tutorial that walks you through the process from starting at zero and going to a deployed RIA Suite application. Really, it is quite simple. You just need to add the Project Generator as an external tool in Eclipse. Although it is a bunch of screenshots, this is a common task for Eclipse users and little can go wrong.

    In Eclipse, click Run -> External Tools > Open External Tools Dialog… and point a new external tool to your “/addon/generators/build-setup.xml” from the RIA Suite install. Your window should look like this:

    0ToolConfiguration

    Now you’ll have the menu entry for Run -> External Tools -> ULC Project Generator, which you should click now. You’ll be prompted for a project name and whatnot, and a sample Contacts application will look like this:

    1GenerateProject

    The script runs and you now have a project on disk that can be run. Just click to File -> Import to import it, navigating to where it is on disk. Your import screen should look like this:

    2ImportProoject

    If it all goes well your project should be open and your Project Explorer should look like this:

    3ProjectView

    Add the Lombok Jar
    We need to add the lombok.jar to the Contacts project, add it to the build classpath, and click Refresh to make sure Eclipse is aware that something changed.

    Copy the lombok.jar to ./Contacts/lib/development directory in your project. Then edit the project properties (right click the Contacts project and select Properties), select the Java Build Path entry, and add lombok.jar as a Jar. Should look like this:

    4AddLibrary

    Create Domain Object
    Let’s add a domain object with JPA persistence to our project. A Contacts application must show a Contact, right? This looks about right:

    package org.sample.contacts.domain;
    
    import javax.persistence.*;
    import lombok.*;
    
    @Entity
    public @Data class Contact {
        
        @Id
        @GeneratedValue(strategy = GenerationType.SEQUENCE)
        @Getter(AccessLevel.NONE)
        @Setter(AccessLevel.NONE)
        private Long id;
        private String name;
        private String email;
        private String primaryPhone;
    }
    

    Let me explain a few details… The class is marked @Entity so that JPA persistence works. The class will map to a Contact table in the database. The class is marked @Data so that lombok will weave in getters, setters, toString, equals, and hashcode methods. The @Id annotation on the “id” field marks that field as the primary key to JPA, and the @GeneratedValue means the field auto increments. I use the GenerationType.SEQUENCE strategy because I plan on deploying to Google App Engine, otherwise this parameter here is unneeded. Lastly, getters and setters are supressed on the id field by adding @Getter(AccessLevel.NONE) and @Setter(AccessLevel.NONE). If you don’t do this then the view-layer automation of Ria Suite is going to, by default, provide you with edit fields for the id, which you should not do.

    Generate the View Layer
    To generate the view layer, click Run -> External Tools -> “Contacts generate-beans-view”. This tool was installed for you by the Project Generator. Running it generates a simple Create-Read-Update-Delete (CRUD) interface with a table, buttons, and entry editor. You’ll see a couple new classes and property files in your application after you run the tool.

    Run application
    Last thing to do is run the app. Click Run -> Run History -> Contacts (again installed by the project generator), sit back, and behold an application.

    5DeployedApp

    That’s it!

    Next step is to deploy to Google App Engine using that Contacts-copy-to-GoogleApp tool that the generator installed, but that is a blog post (and task) for another day.

    Enjoy!


    Code Generation on the JVM: Video and Slides

    July 14th, 2010

    Two weeks ago I spoke at the Chech Java User Group (CZJUG) on the topic of “Code Generation on the JVM”. Some of the technologies covered are Lombok, Groovy, GContracts, Spock, AST Transformations, Spring Roo, and other fun stuff.

    The slides are available at: http://github.com/HamletDRC/presentations/blob/master/asttransformations/asttransforms_czjug.pdf

    As a fun aside: my Ubuntu laptop went crazy the night before and I spent all day before the JUG reloading Linux on my vacation. In the end, I had to switch to my wife’s Mac to do the presentation and live coding. I got the Macintosh fully configured and, during the 1st presenter, realized that I had no VGA output on the Macintosh. Oh geez. The final solution was to share my desktop, have an audience member VNC to my wife’s machine, and project the desktop from the audience. It worked and I’m glad I didn’t have to give the whole talk in chalk on the blackboard (although that would have been a fun challenge).

    Enjoy the video!


    Jazoon ‘09: Securing AJAX Applications

    June 24th, 2009

    Session title: Securing AJAX Applications
    Speakers: Moritz Kuhn, Philipp Färber – AdNovum Informatik AG

    The subtitle of this talk is: “New threats and defenses?” Does the question mark imply that they will question the existence of new threats?

    Speaker Moritz begins by citing some interesting attacks which took place recently, one of which took down myspace for a period of time – apparently using a simple JavaScript payload.

    Proceeds to explain the “Same Origin” policy, which is designed to prevent a JS script in one frame from accessing the DOM in another frame. Note that this is enforced at the Window’s border. However, the rules are very complex and apply to cookies, XHR… and several other areas.

    XMLHttpRequest has a stricter security model, which is often a pain for developers because it is inflexible, yet it is too loose for engineers because it is ambiguous.

    Cross-Site Scripting (XSS) is an attack which exploits ambiguity in Same Origin rules.

    Cross-Site Request Forgery (CSRF) when the victim is logged into an authenticated web application and his browser stores a session cookie for the app. The attackers web page makes the victim’s browser send a request to the vulnerable web app. The victim’s browser appends the cookie to the end of his request.

    Speaker demos these attacks by showing how an attacking app can insert JavaScript code into a calendar; points out that the code could contain anything… reading email for example. Scary stuff!

    How to combat these threats? Philipp takes to the stage…

    Begins by contrasting classic and AJAX architectures, which increases awareness of the technical interactions involved between the parties.

    Looking from the server-side, need to consider that the attack-surface is increased in an AJAX architecture e.g. via exposed services, protocols, sessions, domains. Also: code contains call params and service URLs. Finally, there are concurrency issues.

    From the client side, new attacks are around like JSON hijacking and DOM-based XSS with URl fragments.

    A final observation from the speaker is that one of the consequences of all this is that testing is getting harder. Exhaustive testing is obviously out of the question.

    Counter-measures:

    Input validation, output encoding, service hardening. Retain awareness of the technologies you are using. Defensive design involves avoiding mashup-like services, KISS and using separate domains for public and private data. Points out the fact that the Google domain strategy is open to XSS attacks.

    Some AJAX-specific counter-measures: Know the output’s insertion context (don’t allow angled brackets in the output, for example!); Ensure no sensitive data is sent to the client (be aware what your frameworks are sending!); Prefix all JSON replies e.g. ‘while(1); {”x”:”y”}’; Add a random number to a response and match it up when the next request comes in. This can’t be predicted in advance by an attacker (I like this!); Validate services responses – also in the client; Understand and use a secure framework e.g. GWT, prototype, jQuery…

    Rigorous testing is obviously a must; Designing for security/testing upfront is a must; Test individual AJAX features individually; Simulate malicious requests…

    Conclusion: AJAX means: Old threats + new threats + higher complexity = bad news.

    Summary: I never cease to be shocked by the degree of details and complexity which the developer has to be acquainted with in order to make an AJAX-based app secure. The reality of AJAX development is that in most projects the developer will be focussed on delivering the the core business requirements and getting the look and feel right. With this focus security holes are virtually inevitably.

    A very worthwhile presentation!


    Jazoon ‘09: Java Server Faces at Credit Suisse

    June 23rd, 2009

    Session: Jsf and Ajax in the Credit Suisse
    From: Benjamin Bratkus, Credit Suisse; Micha Kiener, Mimacom AG

    It will be interesting to see what CS has been up to with JSF. My last JSF project finished early in 2008. I look back to it with pleasure not primarily because we used JSF but because we really got to use all of the key JEE features under Glassfish – which worked sweetly. JSF (which included facelets), on the other hand…

    CS began with JSF in 2004. Corporations begin what they are, this resulted in a pilot (2005). Release 1 of their app took place in 2007. Since then CS claims to have one of the biggest JSF-based component libraries around.

     

     
    Framework must support:

    • Realtime data
    • Handle huge data sets
    • AJAX and JavaScript due to security aspects

    …and must achieve acceptance by various architects.

    The speakers also used ICEFaces to achieve the required level of interactivity and security. Specifically: Direct-to-DOM rendering (D2D), page level AJAX on existing components, AJAX Push capabilities.

    Key to achieving efficient push: Asynchronous server push, which will apparently become standardised in the next version of ICEFaces. This approach frees up threads on the server-side, which is obviously essential for scalability.

    Summary: Good talk, competent speakers. I still feel sorry for the average AJAX developer, who despite frameworks like ICEFaces is confronted with myriad non-trivial technical details. Plus, I imagine CS is not confronted with the other big pain for browser-based RIA: Multiple browsers.


    Jazoon ‘09: iPhone development and Java

    June 23rd, 2009

    Title of this session: Development for the iPhone from a Java Perspective
    From: Software Architect Ognen Ivanski, Netcetera

    Note: Netcetera developed the wemlin app for the iPhone – a useful tool for navigating public transport in the ZĂĽrich area.

    Ah… it’s become apparent to me that Ognen will tell us about his personal experience with becoming an iPhone developer, having previously been a Java developer. I have gone through this process myself and so it will be interesting to compare notes…

    Ognen states that the first realisation was that performance, startup-time and UI were kind of new priorities for him. Not really the case for me, I must say. Canoo is known for its RIA experience and therefore these are issues we’ve been dealing with for some time. For the record: The issues which I found most difficult when switching to the iPhone SDK and XCode were:

    - No garbage collection: Clearly I’ve been spoiled by Java
    - XCode: Powerful but nowhere near as comfortable as a typical JavaIDE
    - SCM support: We managed to get Subversion working, but kept running into trouble with things getting out of sync anyway. Best to use the command line

    I certainly agree with Ognen’s observations on XCode: Like me, he missed features such as refactoring and the countless options for viewing, navigating and outlining code.

    Ognen notes that XCode’s visual builder is difficult to get used to but delivers in the end. Possibly like many Java/would-be iPhone developers, I shied away from the visual designer, opting to code from hand instead. Perhaps for my next iPhone app I’ll take a look at it again.

    I agree with Ognen’s observations on Objective C syntax. It’s got a “familiar and yet somewhat strange” feel to it. The behaviour around “nil” seems odd at first, but one quickly learns to appreciate that it pays not to have to check for null values all the time, as in Java code.

    There follows a lot of examples of Objective C Syntax.

    Patterns of note in the iPhone world: Delegate pattern, Target/Action pattern, MVC – which is perhaps truer to the original Smalltalk concept that what we typically see in Java swing, say.

    In summary: A good presentation, but no new insights for someone who’s gone through the process of switching from Java to iPhone development already.