Grails part 3 – Creating your first webapp

Let me shock you with this: Grails does not need Eclipse. It has a beautiful interactive console that helps you in every task, and sometimes it is the only way to obtain certain results. We’ll be using Eclipse simply because most of us had experience with it and it’s f***ing comfortable.

Start your Grails perspective and, in the project explorer, right click->new->grails project. Sit back, it’ll take some time. During this time, maven will work for you to download any requirement to make the beast come to life.

Once it’s done… we’ll you’re ready to go.
Hint: coherence is nice, so I suggest you to create a run configuration as you’d do for any runnable project in Eclipse. So create a new Grails run configuration and set it up like this.

Please note the “Grails Command” field. That is exactly the command Eclipse is gonna issue to the Grails console.
Once you’re done with that… well, I guess you can launch it. But wait… where’s Tomcat? Well, who cares. What actually happened here is that Grails needed Tomcat and either found it in the Grails distribution or downloaded it as dependency.

It’ll take some time because even here, Grails does a basic check of its dependencies and compiles the code, if needed.

Browse to http://localhost:8080/TestProject (or whatever you project name is). You should be presented with something like this:

and I really hope this shows up, because debugging Grails issues is something that definitely requires some experience!

What you see here is a Grails generated page that lists out all the controllers available in the web app. In this case, there are none.

In the next article we’ll try to create our first controller!

Grails part 1 – basic components and concepts

I feel guilty now. I really acted like a fanboy when, in the previous article, I just proclaimed the superiority of the Grails platform, rather than giving useful information.

So here’s what I’m going to do right now. I’ll try to create a sequence of articles describing the key “start points” of Grails. Hints trying to help you  understanding where to start your study. Each article will have some requirements and difficulty I’ll set at the beginning.

Requirements: basic programming, basic web programming, some database programming
Difficulty: introduction 

But let’s start right now, shall we? What I’d like to do today is to name some key components/concepts that will recur during the series.
If you have no idea of what a concept refers to, you should do a little google search before you proceed to the next step, but do not go too much in detail now, let’s just overview the whole thing.

Model View Controller or MVC
I have some sort of mania for this pattern… If you’ve never heard of the MVC pattern, then you really should start googling around now, but in a few words, a MVC is a pattern that should help you separating the model (data retrieval/modification mechanisms and business logic) from and the controller (describes the interaction between the components and the flows) from the view (presentation of the data) as much as possible. Each section should be able to do their job without being involved in the development of the others.
In this way:
- the model part will be in charge of implementing the business logic that regulates the access to the data, and performs the necessary transformations and calculations;
- the controller describes the flow of the interaction between the external agents (user or program), the model and the view;
- the view will create a proper presentation of the data that the controller made available, describing a paradigm the external agent (user or program) will use to interact back with the underlying controller.
It’s not a feature of a programming language, it’s a strategy and some frameworks (like Grails) not only help you applying it, but kinda force you to do so. Some other frameworks show a very weak separation between the model and the controller .
Some web developers working on small projects might not have used one, but MVCs are slowly being adopted also for tiny applications.
What you normally expect from a MVC framework is a specific way to write the flows in the controller and a specific language to write the view (to express the formatting of a variable, to iterate over a collection etc.).
In the Grails world, the model must be written in Groovy (a highly productive dynamic language, very close to Java) and the view in Groovy Server Pages (GSP), a very expressive “design” language.

Object Relational Mapping or ORM
If you come to me for an advice, make sure you have no line of SQL in your code, that is something that would turn me into a beast. Unless it’s very needed (see performance or some unidentified major reason) developers (and web developers) should have abandoned the direct use of SQL long ago.
ORM  is a technique that should improve the way software interacts with RDBMS, reducing the distance between the code and the data. How does this happen? Well, from the developers point of view, what happens is that you don’t really have to deal with tables, columns etc. anymore as tables are mapped to objects. Developers never actually see tables or the technical aspects of data retrieving, update and insertion.
One beautiful side effect of this approach is that since developers do not care much about the underlying database, multiple “dialect” connectors can be written so that from the software point of view, which database plays with its data, is not-a-software-problem.
This topic really requires some background in relational databases, so if you feel a little weak on this topic and your memory links words like “transactional”  to Skyrim, then some more study could help
Grails offers you a superb integration of a persistence layer named Hibernate (how persistence relates to ORM is something you should concentrate your study on). In very few words, this tool offers you the ability to connect to most databases, define schemas and run queries without really worrying about tables and SQL itself. Hibernate can be used in any Java application, but the Grails integration is something that will shock you, even if you already know the tool.

Test Suite
Unit testing and integration testing is what save you from the worst shit ever. Or at least it tries, since you’ll likely be writing your tests yourself!
Could sound boring (and it is) and some might consider it something “added to” the Grails platform, but believe me, it’s not. In these days I’m discovering myself how immense can be its help in fixing ugly code.
Grails offers you two ways of testing your work.
- Unit testing: a very clean way to test your units of code singularly. In short, imagine you could split your code in units as much independent from each other as possible (aka. good code) . Now imagine that you could associate to every unit, another piece of code that tests it with various input sets knowing already what result to expect (unit test). Now when you make some modifications to that code, you can quite be sure that if it passes the tests, the code is not losing compatibility with the previous version! If you don’t know what I’m talking about, see the links at the end of the article.
- Integration testing: a intriguing way to test entire procedures or sequences in an environment the resembles a full running environment. For example, this allows you not only to verify how the Encoder class encodes the user password, but also how the full login process works in all the various contexts.

These are the concepts behind the major key components of Grails.
If you want to follow the path of Grails, I think you should make sure that you already know what these concepts are about, at least for what concerns the theory.

Here some useful links:

Model-View-Controller
- High level explanation http://en.wikipedia.org/wiki/Model_view_controller  .
…further readings…
- Some more reading on how to use Spring MVC outside the Grails framework http://static.springsource.org/spring/docs/current/spring-framework-reference/html/mvc.html

ORM
- High level explanation http://en.wikipedia.org/wiki/Object-relational_mapping
- Data modeling http://www.agiledata.org/essays/dataModeling101.html
…further readings
- Hibernate… of course http://www.hibernate.org/

Unit testing

- More than sufficient http://en.wikipedia.org/wiki/Unit_testing
- JUnit http://www.junit.org/

Grails – the search is over

 And it is over for real. Imagine a full blown on-rails platform that…
- runs on almost any servlet container (Tomcat, Jetty, etc.);
- allows you to create web applications using a beautiful integration of Spring MVC
- … using a nice dynamic language (Groovy) that is fully compatible with Java
- … but not stopping you in any way to use Java itself if you like (for most functionalities);
- interacts with the database with the most impressive Hibernate integration (GORM) I’ve ever seen;
- makes it easy to create templates using a very simple yet powerful language (GSP);
- has a huge availability of plugins, from captchas, to optimizations, from LDAP to analytics;
- integrates a powerful testing suite;
- runs ‘convention-over-configuration’ for 99% of the features;
- the Eclipse plugins guide you during the development in the most useful way;
- its learning curve is gentle;
- it’s created and maintained by SpringSource!

Now, I’ve never been much satisfied by on-rails platforms, seriously, it’s not my world. Even more, being more a software engineer than a web engineer, my interests in that kind of products have always been kinda mild.
When I first met Grails (10 months ago) I was skeptical -as always- but it took me less than 1 hour to realize what was going on in my computer, and I was shocked. Everything was over the top. The persistence layer is SUPERB, the separation of the controllers and the UI is perfect as much as the languages needed to develop them (and their organization inside Grails). The time needed to understand all the basics? 1 hour.
Still, I HAD to start a test project and see how much my first feeling was correct and be certain this marvel of technology was ready to suffer the pains of a real full blown production environment. Folks, it really met my expectations. This thing… is amazing.

Of course it has some downsides, in 10 months I had my oh-oh here and there.
First of all, in production you might not need a super powerful machine to run it (unless your traffic needs it), but in development… well get ready to heat your processors and disk.
Secondly (by the time I’m talking, I’ve haven’t seen Grails 2 yet), sometimes the development environment simply stops working. “This is broken, this does not compile” you know, the kind of mysteries that makes you bang on the keyboard like a monkey. You just need to get in touch with Grails common oopses to fix that in an instant, but the very first times, it’s going to be a little troublesome. Note: this kind of issue are likely related to the Eclipse plugin, rather than Grails itself.

I’m no fanboy. I hate fanboys. But this framework makes me very close to one…

GO GRAILS! 

A good article about the garbage collector

Essential and very accurate article about JVM garbage collection by Alexey Ragozin:

http://aragozin.blogspot.com/2011/12/garbage-collection-in-hotspot-jvm.html

Yet another JVM programming language : XTEND

Hello!

Since this is my major trend these days, here’s another language for the JVM! Err… nope, not exactly. The language subject to our attention is a clean, fast language that then gets converted to Java language!

Endorsed by the Eclipse Foundation  -people we like and respect-, XTEND includes all the must-have functionalities these new languages must have.
No intention to be mean… but the syntax looks quite like Groovy, but hey… I always agreed with the thesis that every good idea should be copied to extend the benefits of a great improvement, and I’m not going to regret it now!

Sure thing the Eclipse support is gorgeous.

Give it a look, it’s pretty neat!

http://www.eclipse.org/Xtext/xtend/

Java’s not old, just needing a grandson

For the ones saying Java is old and is following the path of Cobol: get lost. Java is and will be, for some long time, a bleeding edge in software programming.

Sure it’s changing it’s target, and it’s doing that naturally. In the early ’00s there were Java desktop application popping up anywhere. It was slow, not responsive at all and ugly. Things changed during the years, SWT became a super glam framework in Java desktop programming and I used it A LOT with good results (but can’t say pleasure). I agree there are far better languages and frameworks for the client side, but no matter what Apple says, Java is here and will stay.

But the truth is the best Java ecosystem is server side. J2EE applications rock the enterprise, servlet containers rock web applications.

Still, Java is getting old. Being old means being wise, having a huge background and being able to face almost any situation. It’s not the framework. It’s the language. And languages are subject to fashion, changing needs, will to improve.
Especially with this recent big interest in functional languages an mixed “compiled+interpreted” languages, Java is helplessly behind.
Reinventing a language (some people do…)  must be a beautiful experience. I never tried that and probably never will, but it must shake your world. Still, as my friend and researcher Francesco Zanitti told me yesterday (he’s working on much more advanced stuff compared to my today’s topic), theory and real world are so distant in computer languages some can get demotivated.

Java rocks, but is in need of a grandchild. A successor. A language that can take the hierarchy of Java and bring what’s been done so far to another level, adding new possibilities rather than limiting what’s available now to get to a new frontier. Some may say this limits the possibilities to improve, to invent, but the fact is this is not a contextual language, nor a scripting engine. I’m talking about a commercial language that has to be able to add spice to something that already works well. That can handle complexities that can scare the crap out of you. It doesn’t necessarily have to be “born from Java”, it can also come from elsewhere, but the fact stays: to obtain adoption, you have to pull current knowledge and wisdom out of Java.

If I had solutions to this dilemma, I wouldn’t be here writing. Still I have some major suggestions for you to extend your interests on what’s out there:

Scala is a very intriguing, elegant programming language. It integrates both object oriented and functional programming and can interact with Java pretty well, resulting a flavour that is, in my opinion, unique. The project is mature and the success stories are not few: one for all Twitter.

my pick:
Groovy
  shares many things with Scala, also the syntax has a lot in common. Object oriented and functional programming work as one and the interaction with Java is absolutely surprising (no extra work at all). The learning curve is ridiculous because Groovy basically accepts all Java syntax and lets you learn what else it can offer. It’s not too elegant, nor too fast,  but incarnates beautifully what I meant in this article. The project is not fully mature in my opinion, but is endorsed by SpringSource and used as main language in the Grails web framework (that has many success stories).

I’m certainly missing some great tools. These are just two good languages I had the luck to work with directly and had fun with. I’ll be writing more about Groovy soon, but in the meantime, take your time to try them yourself, it’s worth it.

LinkedIn API, OAuth and Scribe

Hello everyone.
We know OAuth is a beautiful authentication service… in terms of concept. But when it comes to implementation, it’s a real pain in the ass. I found myself into fighting against it using Java to authenticate on LinkedIn, the popular reputation network. After a few minutes I was crying like a baby. It’s not impossible to do it by yourself, but the patience required is more than I could offer.

So I found out this library, named Scribe written by the brilliant software engineer Pablo Fernandez  that definitely helped a lot.
I copied and run his server side authentication example and worked like charm.

I’m taking his example for Twitter right from here site here (hope you don’t mind Pablo) https://github.com/fernandezpablo85/scribe-java/wiki/getting-started :

OAuthService service = new ServiceBuilder()
                           .provider(TwitterApi.class)
                           .apiKey("your_api_key")
                           .apiSecret("your_api_secret")
                           .build();
Token requestToken = service.getRequestToken();
String authUrl = service.getAuthorizationUrl(requestToken); Verifier v = new Verifier("verifier you got from the user");
Token accessToken = service.getAccessToken(requestToken, verifier); // the requestToken you had from step 2
OAuthRequest request = new OAuthRequest(Verb.GET, "http://api.twitter.com/1/account/verify_credentials.xml");
service.signRequest(accessToken, request); // the access token from step 4
Response response = request.send();
System.out.println(response.getBody());

And guess what, it worked like charm with LinkedIn also (just changing a few details you can find by yourself).

This is all beautiful… a pity what I had to implement was a client side authentication. The user authenticates on a LinkedIn popup, generates a cookie with an auth token in it that is then sent to our server that must use it run an exchange with the LinkedIn server to obtain a real access token… This is a very powerful authentication process, but implementing it is, again, a work of patience.

And again, reading through LinkedIn developers forums, Scribe shows up again, used like this:

OAuthRequest req = new OAuthRequest(Verb.POST, "https://api.linkedin.com/uas/oauth/accessToken");
req.addBodyParameter("xoauth_oauth2_access_token", jsnpToken);
Token token = new Token("","");
service.signRequest(token, req);
Response resp = req.send();
String body = resp.getBody();

where “jsnpToken” is the auth token passed through the cookie and “body” contains a string describing the real access token you’ll use to sign further requests.

Wasn’t that easy?

Thanks Pablo!

Java : Final oddity

Hey, I’m back.

I was captured in optimization facts lately and I ended up chasing the true advantages in using final stuff correctly (in Java of course). But much before I could state I have an opinion, I found myself trapped in a strange JVM… mystery.
What I wanted to understand is if the JVM can listen to our ‘hints’ to take the final stuff  and use it inline.
This topic has been subject of many talks, mostly because it’s hard for the JVM to determine whether a field won’t change at runtime or not. This could be obvious at first sight: final fields won’t change. But when reflections come into play, well… you’ll never know.
So can reflections change a final field? This is the question. And the answer is: WHO KNOWS? If you look at this document, you’ll notice it’s a long and painful story.

Since there’s nothing better than trying stuff yourself, I tried to discover it by doing a simple test program.

public class Malicious {
	public final int testField = 5;

	public static void main(String[] args) throws Exception{
		Malicious m = new Malicious();
		Field f = m.getClass().getField("testField");
		f.setAccessible(true);
		f.setInt(m, 7);
		System.out.println("f: "+f.getInt(m));
		System.out.println("m.testField: "+m.testField);
	}
}

Before I tell you the results, let me first say that I used:

- MacOSX 10.6.4
- 1.6.0_22
So you won’t get upset if you get different results on different environments.

RESULTS:
f: 7
m.testField: 5

Honestly, this makes no sense. No security exceptions, nothing, just different values. And of course, if I remove the final keyword, what I get is:
f: 7
m.testField: 7

I’m honestly happy to state that a final field cannot be modified via reflections. I’m less happy to say the behavior is not supported by a homogeneous communication because I only got a security exception when I tried to remove the setAccessible line.

SVNKit, OSX, WebDAV and a wagon of shit

Hello everyone,

I’m back writing on this abandoned blog telling you a sad story about unstable technologies and epic fails.

SVNKit is a marvelous library that lets you write programs which interact with Subversion repositories and working copies. If you’re Eclipse users you’re probably using it as connector in Subversive.

It’s a wonderful tool, I love it but the disaster I’m going to tell you about… well, will clearly show you that not all the glitter is gold.

Scenario:

- A WebDAV server
- Various OSX clients with Eclipse (and SVNKit of course) on board which mount a personal remote FS

The users easily connects to the webdav server, connects Eclipse workspace to the remote FS, work work work, and then commit. Work work work, and then commit. Work work work and then commit.

The big FAIL in this story is as follow:
The commit operation via SVNKit brought the  mounted unit in a strange state where whenever you save, the saved data never reach the WebDAV server. Everything looks good on the client, but the server does not get a single update. The only one understanding there’s something wrong is SVN that, if asked, tells you no resources have been modified since last commit, but of course you don’t keep checking over and over do you?
If you disconnect the unit at this point, all changes since last commit will be lost!

I’ve checked and double checked, ANY program based on SVNKit melts your mounted unit.

Using native Subversion solves the problem entirely, but how many tears did I cry for this? LOTS.

Hope this helps!

Ah, almost forgot: useless to say that on Linux and Windows worked like charm!

Mad snippet of the day (too much power for a useless idea…)

Especially written for a servlet container… just guess what it does…

public <E>E toObject(HttpServletRequest request, Class<E> type)
                 throws InstantiationException, IllegalAccessException {
  E inst = type.newInstance();
  Method[] mets = inst.getClass().getDeclaredMethods();
  for(Method m : mets){
    if(m.getName().startsWith("set"))try{
       String varName = m.getName().
                           substring(m.getName().indexOf("set")+3);
       varName = Character.toLowerCase(varName.charAt(0))+
                                         varName.substring(1);
       String val = request.getParameter(varName);
       if(m.getParameterTypes()[0]==Integer.class)
           m.invoke(inst, Integer.valueOf(val));
       if(m.getParameterTypes()[0]==Boolean.class)
           m.invoke(inst, Boolean.valueOf(val));
       if(m.getParameterTypes()[0]==String.class)
           m.invoke(inst, val);
      }catch(Exception e){e.printStackTrace();continue;}
     }
   return inst;
}
Follow

Get every new post delivered to your Inbox.