Wednesday, August 10, 2011

Git: publishing a site after push

Today we're going to do an amazing thing: publish a website using Git :) This will be very similar in outcome as the deployment model used by Heroku :) Interested? Read on...

The usual thing is that you have a folder that's exposed on the web and using your favorite web browser you can make the server send you files stored in the folder in question. There's nothing special about that. What's actually very annoying is that every time you do some changes there's a need to upload the new files to the server.

There's been tons of different solutions to that issue ranging from automated synchronization agents to manual ftp operations. The one solution I like most is to use Git to do the heavy lifting for me. Here's how it's done.

You have a repository at, let's say, /srv/git/my-website.git and want to keep the actual files to be served at /var/www. To make git populate the latest versions of your files once you've pushed your changes you need to:

1. Create a file named /srv/git/my-website.git/hooks/post-receive with the following content:
#!/bin/sh
GIT_WORK_TREE=/var/www git checkout -f
2. Set it's permissions so that it is executable
chmod +x /srv/git/my-website.git/hooks/post-receive
3. Set the ownership of /srv/git/my-website.git/hooks/post-receive so that whatever user runs the server process can execute it.

And before I forget: the destination folder needs to already exist and the user that's managing the repository (for example "git" or "apache") needs to have read/write access to that folder!

And that's it! Once you do a git push your changes will be automatically propagated to the proper folder :)

Have fun!

Monday, August 1, 2011

Java 7 and diamond operator

Java 7 has finally been released. After 5 years we've finally been given a new toy to play around with. Better, faster, lighter.. One would hope for a breeze of modern features in the language after reading statements like "Type inference" and so on.

What I'd like to make sure everyone understands is that the so called "Diamond operator", further more specified by Oracle as "Type inference for generic instance creation" is nothing more than a lie sold to us once again. Let me show what I mean.

Java 1.6 code:
List<String> names = new ArrayList<String>();
In this case there's nothing to inference because the code is given to the compiler with all the details. Now what actually happens when the code gets compiled?
The right-hand operand (as well as the left-hand side) is stripped of the generic parameter because of the type erasure, one of the most incredible nonsense in Java. So in fact it's no different that saying
List names = new ArrayList();
In the light of the last statement here's what the creators of Java 1.7 made to ease our pain:
List<String> names = new ArrayList<>();
In this case instead of forcing you to specify both generic arguments they only make you specify it once (where the compiler will actually need it). That's it. The type erasure still takes place so the compiler really couldn't care less about what kind of generic freak show is being assigned to the variable as long as it satisfies the assignment (which in this case has nothing to do with generics but simply with the fact that an ArrayList is a List).

Now let's look at what type inference looks in other languages. Let's start with Groovy:
def names = new ArrayList<String>();
Here we see that the type of the names variable has been inferred to match the type being assigned to it. In Scala the situation is almost identical:
var names = new ArrayList[String]()
Again here's a real type inference in action.
Let's switch platforms for a moment and see how it's done in C#, a statically typed language for .NET:
var names = new List<String>();
What you see here is once again an additional keyword that marks the variable as being subject to type inference.

At the end of the day for me it is more important what the variable name is and that's what exposed in C#, Groovy, Scala and pushed to the background with all the type declaration fuzz in Java.

We can go on and on with examples from other languages where type inference goes beyond the simple fact that you don't need to specify the generic type of the variable twice. There is however one thing that can make you wonder what the hell is actually the type inference in Java style for? Let's see the following example:
List<String> names = new ArrayList<String>();
names.removeRange(0, 1);
This code obviously will not compile but this snippet (in Scala) will:
var names = new ArrayList[String](); 
names.removeRange(0, 1);
Why is that the case? In the Java snippet what we're doing is we're specifically saying that he variable is of type List<String> not ArrayList<String> which in turn means that the method removeRange is not available. In the second example what we're saying is that the variable names should be of type ArrayList[String] because that's what the type inference will ultimatelly figure out. But do we really want to have a List in the Java version? If so why do we specify ArrayList as the class to define the construct that we want to instantiate? Shouldn't we have that instance injected from somewhere else and then code against an interface instead? And if we're instantiating an ArrayList do we really need to strip ourselves from the actual thing that we have oh so obviously specified and play cripples just for the fun of it? Or better yet here's how the Java code could have been written:
List<String> names = ArrayList<String>();
((ArrayList)names).removeRange(0, 1);
Cute, isn't it? And so damn readable!!!

Again we can go on and on with examples and theories what actually is type inference and if what Oracle is feeding us is a trick to make us believe Java is still evolving. To my liking there's no point in coding in pure Java, a language that didn't see a major change for 7 years (September 30, 2004 where generics have been introduced). Or do you think that underscores in integer literals deserve to be taken as a major breakthrough? :D

Have fun!

Monday, July 25, 2011

Grails, Camel and Hibernate session

It's been a while since I thought about manually opening Hibernate sessions to do some work on the database. The usual thing is simply to call one of the GORM methods like get() or save() and have the framework tackle all the bits and pieces regarding low-level Hibernate usage for me.

From time to time however it is important to have a high-level understanding of what's going on behind the scenes. One example of that is saving entities in services utilized as part of Camel routes. But let's start from the beginning...

In Grails opening Hibernate session is handled by a Spring class called OpenSessionInViewFilter. This is a filter that opens a Hibernate session before anything else is happening and closes it after the processing is done. With this filter in place a Hibernate session is available throughout the whole request cycle.

When doing processing in Camel we're in a separate thread completely outside the normal Grails request processing so there's nothing there to open the Hibernate session for us. As a side note one needs to remember that the same happens in pretty much every case where a separate thread is fired to do some processing. In all those cases Hibernate session is not available.

But I still want to use GORM in those places! How can I open a session manually?

Well, that's the easiest thing ever. GORM-managed entities expose a method called withNewSession that takes a closure with one parameter (the newly created session) and life is good again.
To make this more common I'll give you two other examples of such a method: withTransaction and withSession. The first one fires of a new transaction and closes it after the processing is done and the second one is kind of a utility that allows you to access the currently active Hibernate session if you find yourself in need doing so.

I hope this will save someone some time :)

Friday, July 22, 2011

Grails and Spring inc.

I just found a very nice article by Peter Ledbrook showing how you can integrate a regular Spring MVC part of your application with Grails. If you need to do any sort of Spring-related stuff in your Grails application I suggest you check it out!

http://blog.springsource.com/2010/06/08/spring-the-foundation-for-grails/

Have a nice day!

Grails, routing plugin and GORM

I's been brought to my attention today that it is possible that Camel routes start sooner than some of the other services in Grails (GORM in particular). This leads to issues like missing methods in domain classes. To get around this problem you can do as follows:

In your route definition add the .noAutoStartup() part like this:
from('direct:foo').routeId('myRoute').noAutoStartup()....
In BootStrap.groovy's init closure add the following code:
import org.codehaus.groovy.grails.web.context.*
[...]
def ctx = ServletContextHolder.servletContext.getAttribute(GrailsApplicationAttributes.APPLICATION_CONTEXT)
ctx.camelContext.startRoute('myRoute')
This will give you the possibility to start and even stop a route anytime you want.

You can read more on this topic on fusesource.com.

I hope this will help someone :)

Tuesday, July 19, 2011

Grails routing 1.1.3 released!

I'm happy to announce the immediate availability of the routing and routing-jms plugins. The major theme for this release is hot reloading of Camel inner-workings when service classes are changed.

So.. well... it works. For the most part at least. It wasn't easy but let's examine the changes and new capabilities one step at a time.

Apache Camel.

In Apache Camel there's no obvious way to force the routes to re-get the bean from Spring context. An endpoint caches an instance of BeanProcessor that's created with ConstantBeanInfo instance and that's pretty much it.
Thankfully the BeanProcessor instance is not final and is lazy initialized so if you force it to be null by calling setProcessor(null) the next time the endpoint is called it needs to re-create the processor and all is good. It's a pity no one thought of a "forceReinitialize" method in Camel but this way works too.

Grails.

In Grails it is pretty much standard that you are allowed to overwrite the existing instance of a service class with a new implementation. This mechanism is sort of baked in into the core.
However when reloading services that are marked as transactional there's some AOP going on with cglib and caching that I couldn't quite crack so those kind of services when reloaded will produce an exception that says "SomeService cannot be cast to SomeService" or something of this sort. I'll have to get back to it some day and figure out if this is a general problem with Grails or if it is something I'm missing in my onChange handler. For now if you need your method to participate in transaction you'll have to manually call the withTransaction { } helper.

Bottom line.

The bottom line is that you finally can use the routing plugin to do normal Grails development and it should catch you with no surprise (other than the transactional services...). Go and give it a shot. Let me know if it works for you!

Happy Cameling!

Grails routing plugin - report from the battlefield

Just wanted to let you all know that I've resumed work on improving the routing plugin for Grails. There's already version 1.1.2 that introduces a new method added to controllers, services and (if Quartz plugin is installed) jobs that allows you to send messages with headers.

The next task however isn't simple and will take some time. It's the long standing problem with Camel routes that target beans that are reloaded.

Will see where this will lead me.