Something just like the creation of Java it self, is happening again. Software market place needs to talking in a more higher level languages rather than Java I think. Business on demand pressures the market to create and use more productive tools and technologies.
However, I as a developer need to write some parts of the applications using a little bit lower level language in many situations. Moreover, the huge amounts of developed and ready to use Java libraries such as source codes, jar files, and open source solutions warn me to prevent of reinventing the wheel. So, I align my approach with using the Groovy and Grails and Java classes in source code together just to boost the development and walk with bigger steps; Furthermore, I keep using of Java libraries whenever I need.
There are many situations that you need to use Java in a Grails application. This is more than using just JVM and importing jar libraries. I mean I prefer to user clear Java source code in the Grails application to have respect for the scripting concept of Groovy even in Java classes.
Here we will use a particular Java source code in a Grails application.
Assume below particular Java class:
package com.amir.util;
class HelloWorld {
public static String getMessage() {
return "Hello World!";
}
public static String getMessageFor(String str) {
return "Hello "+ str +"!";
}
}
I am going to use HelloWorld.java instead of HelloWorld.class. Then I will be able to modify it whenever I need and Grails will compile during each "grails run-app".
To create HelloWorld Grails application you first need to give the grails a create-app command:
$> grails create-app helloworld
This will create a new directory inside the current one that contains the project. You should now navigate to this directory in terminal:
$> cd helloworld/src/java
Now you need to create the packging folders:
$> mkdir com
$> mkdir com/amir
$> mkdir com/amir/util
The Java class should be find in this path:
helloworld/src/java/com/amir/util/HelloWorld.java
Now come back to the helloworld folder which is the root folder of the application and create a hello controller:
$> grails create-controller hello
This will create a new controller in the grails-app/controllers directory called HelloController.groovy. You need to modify it to call the Java HelloWorld class.
$> gedit grails-app/controllers/HelloController.groovy
And make it as below:
class HelloController {
def world = {
render HelloWorld.getMessage() + " , "
render HelloWorld.getMessageFor(" Amir ")
}
}
Now start-up the container with run-app command:
$> grails run-app
This will start-up a server on port 8080 and you should now be able to access your application with the URL: http://localhost:8080/helloworld
Job done! You used a clear source Java class instead of the compiled one in a Grails application. Everything is just scripted!