groovy unleashed

Download Groovy unleashed

Post on 23-Jan-2018




1 download

Embed Size (px)


  1. 1. Welcome To Groovy! The Catalyst Language for Programmers Presentation By -Isuru Samaraweera
  2. 2. Agenda Introduction to Groovy Key Features Closures Operator Overloading Array Slicing and looping Collections Dynamic Methods/Mixins and Properties Regular Expressions File IO Database Operations
  3. 3. What is Groovy? Java-like scripting language for the JVM Dynamic Language Inspired by Ruby,Python,SmallTalk and Perl Open Source language Apache2.0 license Seamless integration with Java Follow the mantraJava is Groovy,Groovy is Java Web Application Development Groovelets,GSP,Grapplet Sole alternative dynamic language for the JVM fully supporting frameworks like Spring, Hibernate Grails Coding by Convention Mobile Application Support Official web site
  4. 4. Installation and Configuration Prerequisites JDK1.4 or higher installed and system path should point to %JAVA_HOME%/bin Download Groovy distribution from Unzip the groovy archive Set the GROOVY_HOME environment variables. Add %GROOVY_HOME%bin to your system path Try opening groovyConsole.bat Eclipse Plug-in IntelliJ Idea Plug-in-Community edition
  5. 5. Key Language Features Pure Object Oriented 3.times { println "hello" } Dynamic Typing/Duck typing Closures Currying Operator Overloading Array Slicing Dynamic Methods Expandos Static imports Annotations Covariant return types POGO support Mixins
  6. 6. Java Vs. Groovy No of line Comparison Java Code for (String item : new String [] {"Rod", "Carlos", "Chris"}) { if (item.length() println something } george.say("Hello, world!") george = new Wombat().mixin(FighterType) william = new Wombat() georage.getFighter() // returns william.getFighter()//error
  7. 31. Dynamic Properties You can also override property access using the getProperty and setProperty property access hooks, Dynamically class Expandable { def storage = [:] //Empty MAP def getProperty(String name) { storage[name] } //AUTO RETURN void setProperty(String name, value) { storage[name] = value } } def e = new Expandable() = "bar" println //OUTPUT: bar
  8. 32. Regular Expressions Groovy supports regular expressions natively using the ~"pattern" expression, Which compiles a Java Pattern object from the given pattern string. Groovy also supports the =~ (create Matcher) and ==~ (matches regex) operators. Packages that are used in Groovy for RegEx import java.util.regex.Matcher import java.util.regex.Pattern Regular expression support is imported from Java. def pattern = ~/foo/ assert pattern instanceof Pattern assert pattern.matcher("foo").matches() def matcher = "cheesecheese" =~ /cheese/ assert matcher instanceof Matcher answer = matcher.replaceAll("edam") def cheese = ("cheesecheese" =~ /cheese/).replaceFirst("nice") assert cheese == "nicecheese"
  9. 33. Works with standard Java Reader/Writer , InputStream/OutputStream ,File and URL classes Message Passing Using Closures new File("foo.txt").eachLine { line -> println(line) } Dont Bother about Resource Closing Mechanism Groovy Methods will handle it. def fields = ["a":"1", "b":"2", "c":"3"] new File("Foo.txt").withWriter { out -> fields.each() { key, value -> out.writeLine("${key}=${value}") } } - No Reader / Writer Object Handling Handle the resource for you via a closure - which will automatically close down any resource if an exception occurs - No Data Piping (Stream Management) - No Exception Handling The eachLine() method ensures that the file resource is correctly closed. Similarly if an exception occurs while reading, the resource will be closed too. File Input / Output
  10. 34. Executing External Processes Groovy provides a simple way to execute command line processes. def process = "ls -l".execute() { line -> println line } ==================== Process p = "cmd /c dir".execute() println "${p.text} ==================== def initialSize = 4096 def outStream = new ByteArrayOutputStream(initialSize) //STREAMS def errStream = new ByteArrayOutputStream(initialSize) def proc = "ls.exe".execute() proc.consumeProcessOutput(outStream, errStream) proc.waitFor() println 'out:n' + outStream println 'err:n' + errStream
  11. 35. SQL can be more Groovy - 1 You can perform queries and SQL statements, passing in variables easily with proper handling of statements, connections and exception handling. import groovy.sql.Sql def foo = 'cake def database = Sql.newInstance( "jdbc:mysql://localhost:3306/mydb", "user", "pswd", "com.mysql.jdbc.Driver") database.eachRow("select * from FOOD where type=${foo}) { println "Smith likes ${}" } Thanks to closures.
  12. 36. SQL can be more Groovy - 2 You can perform queries and SQL statements, passing in variables easily with proper handling of statements, connections and exception handling. import groovy.sql.Sql def foo = 'cheese def database = Sql.newInstance( "jdbc:mysql://localhost:3306/mydb", "user", "pswd", "com.mysql.jdbc.Driver") def answer = 0 sql.eachRow("select count(*) from FOOD where type=${foo}") { row -> answer = row[0] } Println (Our menu has $answer dishes to choose from!) Thanks to closures.
  13. 37. SQL can be more Groovy - 3 You can perform queries and SQL statements, passing in variables easily with proper handling of statements, connections and exception handling. import groovy.sql.Sql def foo = 'cheese def database = Sql.newInstance( "jdbc:mysql://localhost:3306/mydb", "user", "pswd", "com.mysql.jdbc.Driver") def food = database.dataSet('FOOD') def cheese = food.findAll { it.type == 'cheese' } cheese.each { println ${} will be delicious" } Thanks to closures.
  14. 38. Why to Thank Closures ? A typical JDBC Program should have these Steps 1. Loading a database driver 2. Creating a oracle JDBC Connection 3. Creating a JDBC Statement object 4. Executing a SQL statement with the Statement object, and returning a jdbc resultSet. try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");//or any other driver } catch(Exception x){ System.out.println( "Unable to load the driver class!" ); } try { Connection con = DriverManager.getConnection(url, userid, password); } catch(SQLException ex) { System.err.println("SQLException: " + ex.getMessage()); } String createString="create table Employees(+"Employee_ID INTEGER,+"Name VARCHAR(30))"; try { stmt = con.createStatement(); stmt.executeUpdate(createString); stmt.close(); con.close(); } catch(SQLException ex) { System.err.println("SQLException: " + ex.getMessage()); }
  15. 39. Reduced code noise in Groovy -Simple code is beautiful code Groovy Will Handle all those common tasks for you, - including Exception Handling, Connection - ResultSet Closing, etc.. import groovy.sql.Sql class GroovySqlExample1 { static void main(args) { database = Sql.newInstance("jdbc:mysql://localhost:3306/words", "words", "words", "") database.eachRow("select * from word") { row | println row.word_id + " " + row.spelling } //CLOSURE wid = 999 spelling = "Nefarious" pospeech = "Adjective" database.execute("insert into word (word_id, spelling, part_of_speech) values (${wid}, ${spelling}, ${pospeech})") val = database.execute("select * from word where word_id = ?", [5]) //Negetive Indexing sql.eachRow("select * from word") { grs | println "-1 = " + grs.getAt(-1) //prints part_of_speech println "2 = " + grs.getAt(2) //prints part_of_speech } } }