Archive for the ‘Groovy’ Category
New DelegatingScript Base Class – Groovy 2.2 feature
Script base class of Compiler Configuration can be customized.
Delegating Script Base Class helps to delegate the calls in a script to a class that has DSL methods/functions & variables.
import org.codehaus.groovy.control.CompilerConfiguration def scriptInfo=''' model="Nexus 5" getModel() ''' class MobileDealer{ String model void getModel(){ println "Mobile : $model" } } def compilerConfig=new CompilerConfiguration() compilerConfig.scriptBaseClass=DelegatingScript.class.name def shell=new GroovyShell(compilerConfig) def script=shell.parse(scriptInfo) MobileDealer m=new MobileDealer() script.setDelegate(m) script.run()
- Line 1 – import package of Compiler Configuration class
- Line 3-6 has the script where the delegate is set and is run finally.
- Line 8-13 has the class declaration of the delegate class MobileDealer. The methods and variables in this class can be reused commonly in scripts.
- Line 15–new instance of compiler configuration is created
- Line 16–DelegatingScript is set as the base class for that particular compilerConfiguration instance
- Line 17-new groovyShell instance is created with the present compiler Configuration
- Line 18-The above “scriptInfo” is parsed to DelegatingScript type
- Line 20-MobileDealer class is set as delegate in the script.
- Line 21-the script is run.
REFERENCE:
http://jira.codehaus.org/browse/GROOVY-6076
Groovy-2.X tidbits
Did you know …?
1.We can know the last element of an array by using -1 as the index
Eg:
def a=[1,2,3,4,5,6,7]
assert a[-1]==7
2.Groovy is much like an English speaking language
Eg : for loop
Earlier in Java,
for(int i=1;i<=10;i++){ System.out.println("Java"); }
*NOTE: Now that Java 8 has introduced Instream for loop with range.
In Groovy,
10.times{ println 'Groovy' }
3.Default access specifiers
- for Class -> public
- for Method -> public
- for variables -> private
4.Groovy generates 2 constructors implicitly
(1) a public constructor
(2) a public constructor where its class variables can be passed as parameters.
5.Values in the constructor can be assgined via Implicit coersion and Explicit coersion too
Eg:
class Season{ def type def month } //Normal way def s1=new Season(type:"winter",month:"December") //Implicit coersion - pre-defining the type of variable. Season s3=[type:"autumn",month:"September"] //Explicit coersion using 'as' def s2=[type:"summer",month:"May"] as Season
6.Underscores can be used in number literals for better understanding
Eg:
long creditCardNumber=1234_2345_3456_4567L
Advancements in languages is happening day by day.
Groovy beta version has come up with advanced features like Delegating scripts, TypeChecking Extensions in Script, project coin(present in Java7) and etc.,However Java 8 is also coming up with much advanced features.
We should bear in mind that language should be only the means to make things simpler.
It’s wise to choose the right one based on our needs.
How to convert your Grails App into a Mobile-friendly App
Assuming that you have already created a Grails application and you have it running in your machine , but you are struggling to fit your application onto different screens like PC, IPad, Tablet, Mobile etc., where your page css is crashing , then it is hightime to check out on RESPONSIVE WEB DESIGN .
RESPONSIVE DESIGN LAYOUT is the layout that makes our application respond to any device screensize that we are using, be it an Ipad /MAC/ Tablet/ Phablet/Mobile screen. Any webpage designed with this layout, will appear attractive, and flexible too.
Here I have tried out Twitter Bootstrap template.
Now to integrate Bootstrap into Grails , it’s enough if we run this command grails install-plugin kickstart-with-bootstrap in our existing Grails app and then change the content type as “kickstart” in the header of every gsp page of every domain class.
Now when we run our application the template would be as below ,
Ajax-Autocomplete in Grails-Bootstrap :
For ajax-autocomplete to work in Grails Bootstrap, all that we need to do is,
- install ajax dependancy plugin by executing grails install-plugin ajaxdependancyselection command.
- add <r:require module=”jquery-ui”/> <r:require module=”jquery”/> tags in the header of kickstart.gsp . These tags when executed, will install jquery and jquery-ui plugin by itself.
- Finally, add the necessary autocomplete tag in the respective gsp page .
The output of Ajax autocomplete working in Bootstrap template integrated with Grails screenshot taken in mobile is shown in the rightside.
However well-designed and worthy be our application , it is of no use until we make it user-friendly and attractive to common people. A product with good appearance and easy-to-use, is known to market on its own. Bootstrap is one of the templates that helps to achieve looks.
The above images that I have shown has the standard Twitter Bootstrap template. However, we can change the design and also add extra features like Carousel, Accordian, Button types, nav-bar, modals etc., in it to give better looks.
Have a great day 🙂
@Canonical = @ToString + @TupleConstructor + @EqualsAndHashCode
ToString in Groovy:
In Java , we override toString() to print results.
In Groovy, this can be achieved simply, by using the @ToString annotation which is one of the A.S.T Transformation traits.(Example given below)
Tuple Constructor:
import groovy.transform.ToString @ToString class Car{ Long carID String carBrand String carModelNo } Car car=new Car(carID:10,carBrand:"Audi",carModelNo:"Q5") println car // O/P: Car(10, Audi, Q5) car.carID=1 println car // O/P: Car(1, Audi, Q5) car.setCarID(4) println car // O/P: Car(4, Audi, Q5)
In a POGO class, the values to the atributes can be set in the above following ways,
- Using a default constructor, where the attribute and its value is set as Key-Value pairs.
- By creating a reference for the class and just denoting ref.attributeName=value
- Setting values using Setter method.
However, values can also be set using Tuple Constructor like the example below,
import groovy.transform.ToString import groovy.transform.TupleConstructor @ToString @TupleConstructor class Car{ Long carID String carBrand String carModelNo } Car car=new Car(15,"BENZ","E-63") println car //O/P:Car(15, BENZ, E-63)
Here , the attribute key is not required. Only values are set directly.
NOTE: Values have to be set only in the order of the attributes listed in the POGO because this Tuple Constructor is a specific positional type Constructor.
The above 2 functionalities i.e., pretty print using toString() and assigning values using Tuple Constructor, along with Equals and HashCode check can be achieved by using a single annotation @Canonical which is imported from groovy.transform.Canonical
Therefore,
@Canonical = @ToString + @TupleCOnstructor + @EqualandHashCode
Have a great day 🙂
memoize() in Groovy
Memoization generally means remembering the output for the already passed input.
In Groovy, memoization is performed using memoize().
An example of memoize() called on closures is given below,
Example:
def toSquare={a-> sleep(2000) a*a }.memoize() //Case 1: println toSquare(5) // O/P:25 --> Got after 2000ms //Case 2: println toSquare(5) // O/P:25 --> Got IMMEDIATELY //Case 3: println toSquare(6) // O/P:36 --> Got after 2000ms
In the above code,There is a closure toSquare.
Here any parameter that is passed into the closure is squared only after 2000ms and above all, the closure is Memoized.
- Case 1 : When the closure is called for the first time and parameter 5 is passed, the computation is done completely . In accordance with the computational flow, the result is printed only after 2000ms .
- Case 2: When the closure is called for the second time and the same parameter 5 is passed, computation is not done and the result is displayed immediately. This is becuase of the memoize(). i.e., By Memoization principle , it stores the calculated value of the input that has been passed already.
- Case 3: Here , a new input is being passed. Computation is done.Result is displayed after 2000ms. However now that , this result for this particular input will be cached.
memoize() –> stores all the new inputs and the corresponding outputs.
memoizeAtLeast(minimum) –> stores atleast a minimum number of results.
memoizeAtMost(maximum) –> stores the maximum number of results specified .
Have a memoizable day 🙂
Quick Note 1: String and GString
There are two different string classes used in Groovy and are java.lang.String and groovy.lang.GString.
Here String can be expressed using a single quote (‘abcd’) or a double quote (“abcd”).
Below is an example,
def a='High-five' assert a in java.lang.String def b="High-five" assert b in java.lang.String def c=5; def d="High-$c" assert d in groovy.lang.GString
From the above example, we can notice that variable a has its value declared in single quote and that of b in double quote. However both of them belong to the same class java.lang.String.
Just a variable’s value with double quote doesn’t make it a GString but, if a variable with double quote has another variable called inside it, by using $ symbol , then it is considered to be of GString type (groovy.lang.GString) .
BE CAREFUL: GString MISBEHAVES at times :
def a=1 def dummyMap=['item-1':'Cookies'] println dummMap.getClass() //O/P: class java.util.LinkedHashMap println dummyMap."item-$a" // O/P: Cookies println dummyMap.("item-$a") // O/P: Cookies println dummyMap["item-$a"] // O/P: Cookies println dummyMap.get("item-$a") // O/P: null println dummyMap.get("item-1") //O/P: Cookies
There are different ways of retrieving values from a Map in Groovy. Few are listed above.
Though in the first place it appears that GString can be used to retrieve values by using $ symbol before the variable name , it also misbehaves at times.
An example is shown above .Misbehaviour in dummyMap.get(“item-$a”) . It provides a null value.
It’s now important for us to understand that ,GStrings are not like Java String.
Java Strings are immutable but GStrings can be mutated.
Check it out below.
Mutation in GString:
def number=5 def dummyString="High-$number" println dummyString //O/P: High-5 dummyString.values[0]=6 println dummyString // O/P: High-6
Since GString is mutable , if used in key , then key is also prone to mutation.Therefore, it’s not a good practice to use a GString in key.
However, we can rectify this by converting GString to String. This is done by using toString() method.Once GString is converted to String, there wouldn’t be any problem because String is immutable.
Therefore, dummyMap.get(“item-$a”.toString()) will give us the proper output.
Otherwise, dummyMap.getAt(“item-$a”) can be used. It is a Groovy method , so groovy implicitly takes care of the String conversion.
Whereas, dummyMap.get(“item-$a”) is a Java Method.Here we’ll have to explicitly specify toString() for conversion.
Apart from the above, multiple lines assigning can be done by using,
Triple Single Quote ”’ and Triple Double quotes “””.
It considers new lines (\n), white spaces, tabs (\t ) and etc.,
Triple Single Quote – reads Multiple Lines but is not supported by GString
Triple Double Quote – reads Multiple lines and is supported by GString.
a='''Horror Movies : Conjuring Evil Dead''' println a assert a in java.lang.String def movieList=['Conjuring','Evil Dead','Grudge'] b="""Horror Movies : $movieList""" println b assert b in groovy.lang.GString
Have a great day 🙂
Groovy is NOT Java !
Groovy is a Dynamic Scripting Language.
It follows the principle of Duck Typing,
“If anything quacks,walks and swims like a duck then the object is considered to be a duck.”
So, if something possesses,
BEHAVIOURS —>quacking, walking and swimming like a duck then
TYPE of that object –> Duck
Therefore based on the behaviour , the type is assigned to a variable.
In Groovy , we use the keyword def to assign any type to a variable.
Here’s an example to illustrate the above.
def a=10 assert a in java.lang.Integer a=0.10 assert a in java.math.BigDecimal a='Aish' assert a in java.lang.String
In the above we can notice few things,
1. Variable a has been assigned to multiple types . This is possible in groovy ,because ‘a’ has been defined as def, which means polymorphic substitution of values is possible.However,whatever value has been assigned finally, that will considered as the final type of a.
2. In the assert statements, java library has been used. Actually Groovy is the extension of Java. GDK(Groovy Development Kit) extends JDK, Java Libraries. Groovy code when compiled , gets converted to Java Bytecode and runs on the JVM.
Groovy follows Java Syntax. That’s why , it’s generally said that, Groovy would be easy for Java Developers.
However, I would like to mark on the above statement that, though Groovy would be easy for a Java developer to understand, the style of Groovy coding is different from Java.
GROOVY IS NOT JAVA and has to be coded in the Groovy way.
If Groovy is the same as Java, then why should the Groovy Language ever be introduced ?
3. I haven’t included any class or method(especially main method) to execute my code because Groovy is a SCRIPTING Language.However, when we write an application, classes and methods are included for clarity.
4. Semi-colons are not used in any of the statements.
Yes, it is not a compulsary in Groovy , to use semi-colons to end the statement. Even, if you use it, it’s not a mistake.
If multiple assignments are being made in a single statement, then semi-colons can be used.
def a=10; b= "I feel up"; c= a+b
In the above case, without semi-colon , you’ll not be able to distinguish and will get Runtime-Exception.
5. In a=’Aish’ The String has been quoted in Single quote.
Double quotes can also be used. Their difference, I will quote it in my next blog.
Groovy has got many advanced features like String Gstring usage, Operators functioning based on t type ,Easy Looping using Closures, minimising Exceptional handling and etc.,
Groovier Updates coming up…
Reflection – Dynamic Typing
Today wanted to add some quick notes on my findings on Dynamic Languages.
To start with, lets look into Reflection.
” REFLECTION” – in common generic terms means a Mirror Image of something.
It carries the same meaning in Java. It means getting the mirror image of a class.
The microscopic details of a class can be explored during the runtime by specifying the class name dynamically. During this process the JVM interacts with the object of unknown type.
Let’s see an example,
public static void main(String[] args) { try { Class class1=Class.forName("aish.vaishno.musicstore.dao.MusicStoreDaoImpl"); Package package1=class1.getPackage(); System.out.println("Package Name with Version : "+package1); String canonicalName=class1.getCanonicalName(); System.out.println("\nCanonical/Standard name of Field class: "+canonicalName); Method[] methods=class1.getMethods(); System.out.println("\nMethods present in Field class:"); for (int i = 0; i < methods.length; i++) { System.out.println(methods[i]); } Class[] classes=class1.getInterfaces(); System.out.println("Interface implemented: "); for (int i = 0; i < classes.length; i++) { System.out.println(classes[i]); } } catch (ClassNotFoundException e) { e.printStackTrace(); } }
While specifying the className dynamically, the .class file of that particular class is opened and examined during the runtime .By Reflection, the package ,Method , Interface, modifier informations and etc.,can be retrieved.
But the demerits of this is ,
- It slows down the performance
- private fields and methods can be accessed.
Reflection concept is used in ,
Spring – while scanning through the packages.
ORM– when data from database is being mapped to the attributes in Entity Bean.
Likewise in Serialisation/Deserialisation, Remote Method Invocation and etc.,
Dynamic Language plays a major role in Rapid Application Development(RAD).
Groovy and Dynamic Language updates coming up.
Reference:
http://javarevisited.blogspot.com/2012/04/how-to-invoke-method-by-name-in-java.html