Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Groovy in daily use

Groovy in daily use

Grygoriy Mykhalyuno

October 12, 2013
Tweet

More Decks by Grygoriy Mykhalyuno

Other Decks in Programming

Transcript

  1. Agenda Groovy for java developers Groovy as DSL Groovy for

    scripts development Some project build on goovy
  2. Agenda Groovy for java developers Groovy as DSL Groovy for

    scripts development Some project build on goovy
  3. Programming language with new features Optional typing Closures Builders Compiles

    to the JVM Compiled, not interpreted Interacts transparently with Java  If you don’t know the Groovy way, use Java Scripts as well as classes Open source project
  4. Groovy cool operators ~= matches operator assert "2009" ==~ /\d+/

    returns TRUE assert "holla" ==~ /\d+/ returns FALSE
  5. Groovy strings Java string def javaString = 'some string' Groovy

    string def val = “String” def gstring = “some ${val}” Escaping def esc = /d:\sss\s.txt/
  6. Grapes and grab Grape (The Groovy Adaptable Packaging Engine or

    Groovy Advanced Packaging Engine) import com.jidesoft.swing.JideSplitButton @Grab(group='com.jidesoft', module='jide-oss', version='[2.2.1,)') public class TestClassAnnotation {  public static String testMethod () {  return JideSplitButton.class.name  } }
  7. Simplifying with clusures placements.findAll { it.booked } .sort {p1, p2

    -> p2.wPrice <=> p1.wPrice ?: p1.creationDate <=> p2.creationDate }
  8. Simplifying with clusures List bookedPlacements = new ArrayList(); for (Placement

    placement : placements) { if (placement.isBooked()) { bookedPlacements.add(placement); } } Collections.sort(bookedPlacements, new Comparator<Placement>() { public int compare(Placement p1, Placement p2) { int r = p1.getwPrice().compareTo(p2.getwPrice()); if (r == 0) { r = p1.getCreationDate() .compareTo(p2.getCreationDate()); } return r; } });
  9. Simplifying with clusures def monthNames = budgets*.month*.shortName List monthNames =

    new ArrayList(); for (MonthBudget budget: budgets) { monthNames.add(budget.getMonth().getShortName()); }
  10. @EqualsAndHashCode import groovy.transform.EqualsAndHashCode @EqualsAndHashCode class Coord { int x, y

    } def c1 = new Coord(x:20, y:5) def c2 = new Coord(x:20, y:5) assert c1 == c2 assert c1.hashCode() == c2.hashCode()
  11. Maps and List is part of language Java Map<String, String>

    map = new HashMap<String, String>(); map.put(“key”, “value”); map.get(“key”);
  12. Maps and List is part of language groovy def map

    = [key:”value”, key1:”other value”] println map.key println map.key1
  13. Maps and List is part of language java List<String> list

    = new ArrayList<String>() for (String val : list) { println val }
  14. Maps and List is part of language groovy Def list

    = [1, 2, 3] list.each { println it } gef collection = list.collect {it > 1}
  15. Groovy sql void storeRerorts() { def db = Sql.newInstance("$databaseUrl", "${databaseUserId}",

    "$ {databasePassword}", "$databaseDriver") [ [id: 1L, reportName: "SuggestionOrder", reportFileName: src/main/resources/export/commercialSuggestionOrder.xml"], [id: 2L, reportName: "commercialSuggestionOrderDetail", reportFileName: "src/main/resources/export/commercialSuggestionOrderDetail.xml"], [id: 3L, reportName: "order", reportFileName: "src/main/resources/export/order.xml"] ].each { db.execute "Insert into Report (Id, ReportName, ReportTemplate) values (?, ?, ?)", [it.id, it.reportName, new FileInputStream(it.reportFileName)] } }
  16. Agenda Groovy for java developers Groovy as DSL Groovy for

    scripts development Some project build on goovy
  17. Why do we need think in DSL? Integer.metaClass{ minutes =

    {delegate * 60 * 1000} } Date.metaClass.'static'.now = {-> new Date()}
  18. Think in dsl def user = users.find{it.login == “name”} def

    user = users.collect{it.login == “name”} 3.times {println it}
  19. Think in dsl turn left then right // equivalent to:

    turn(left).then(right) take 2.pills of chloroquinine after 6.hours // equivalent to: take(2.pills).of(chloroquinine).after(6.hours) paint wall with red, green and yellow // equivalent to: paint(wall).with(red, green).and(yellow) // with named parameters too check that: margarita tastes good // equivalent to: check(that:margarita).tastes(good) // with closures as parameters given { } when { } then { } // equivalent to: given({}).when({}).then({})
  20. EasyB DSL before "initialize the queue for each spec", {

    queue = new Queue() } it "should dequeue gives item just enqueued", { queue.enqueue(2) queue.dequeue().shouldBe(2) } it "should throw an exception when null is enqueued", { ensureThrows(RuntimeException){ queue.enqueue(null) } }
  21. JSON builder import groovy.json.* def json = new JsonBuilder() json.person

    { name "Guillaume" age 33 pets "Hector", "Felix" } println json.toString()
  22. int price = new PriseBuilder() .from(stationA) .to(stationB) .on(route) .with(discount) .calc()

    int price = new PriseBuilder() from stationA to stationB on route with discount calc()
  23. Groovy builder vs XML  <title>  <ua>Тестовий візард</ua> 

    <ru>Тестовый визард</ru>  </title>  <info>  <ua>Цей візард призначений для тестування</ua>  <ru>Этот визард предназначен для тестирования</ru>  </info>  <steps>  <step id="Step1" previousButton="false" nextButton="true" cancelButton="true" finishButton="false">  <title>  <ua>Перший крок</ua>  <ru>Первый шаг</ru>  </title>  <info>  <ua>  На першому кроці нам нічого особливого не треба робити.  Він просто призначений для перевірки різних TextBox.  </ua>  <ru>  На первом шаге нам ничего особенного делать не надо.  Он просто предназначен для проверки разных TextBox.  </ru>  </info>
  24. Groovy builder vs XML  wizard {  title ua:

    "Тестовий візард", ru: "Тестовый визард"  info ua: "Цей візард призначений для тестування", ru: "Этот визард предназначен для тестирования"  steps "Step1": {  previousButton false  nextButton true  cancelButton true  finishButton false  title ua: "Перший крок", ru: "Первый шаг"  info ua: ''' На першому кроці нам нічого особливого не треба робити.  Він просто призначений для перевірки різних TextBox.''',  ru: ''' На первом шаге нам ничего особенного делать не надо.  Он просто предназначен для проверки разных TextBox.'''
  25. EasyB DSL before "initialize the queue for each spec", {

    queue = new Queue() } it "should dequeue gives item just enqueued", { queue.enqueue(2) queue.dequeue().shouldBe(2) } it "should throw an exception when null is enqueued", { ensureThrows(RuntimeException){ queue.enqueue(null) } }
  26. EasyB DSL before "initialize the queue for each spec", {

    queue = new Queue() } it "should dequeue gives item just enqueued", { queue.enqueue(2) queue.dequeue().shouldBe(2) } it "should throw an exception when null is enqueued", { ensureThrows(RuntimeException){ queue.enqueue(null) } }
  27. Agenda Groovy for java developers Groovy as DSL Groovy for

    scripts development Some project build on goovy
  28. Grapes and grab Grape (The Groovy Adaptable Packaging Engine or

    Groovy Advanced Packaging Engine) import com.jidesoft.swing.JideSplitButton @Grab(group='com.jidesoft', module='jide-oss', version='[2.2.1,)') public class TestClassAnnotation {  public static String testMethod () {  return JideSplitButton.class.name  } }
  29. Templete engine <html>  <body>  <% 3.times { %>

     Hello World!  <% } %>  <br>  <% if (session != null) { %>  My session id is ${session.id}  <% } else println "No session created." %>  </body> </html>
  30. Process xls @Grab(group='poi', module='poi', version='3.1-FINAL') import org.apache.poi.hssf.usermodel.HSSFWorkbook  HSSFWorkbook originalWorkbook

    = new HSSFWorkbook(new FileInputStream(filePath))  def originalSheet = originalWorkbook.getSheetAt(0)  println "starting script"  originalSheet.rowIterator().each {  String country = it.getCell(countryColumn).toString().trim();  }  def sqlScript = new File("script.sql")  sqlScript.delete()  sqlScript.createNewFile()  println "writing to file $sqlScript.absolutePath"  regions.each {  def country = it.key  def countryGuid = UUID.randomUUID().toString();  sqlScript.append "--====================block for country $country ================================== \n"  sqlScript.append "INSERT INTO Regions (GUID, Name, Parent) VALUES (\"$countryGuid\", \"$country\", null); \n";  }  }
  31. Sync property files def propertyFileEn = "../src/main/resources/messages_en.properties"  def propertyFileDe

    = "../src/main/resources/messages_de.properties"  Properties propsEn = new java.util.Properties();  Properties propsDe = new java.util.Properties();  new File(propertyFileEn).withInputStream {  stream -> propsEn.load(stream)  }  new File(propertyFileDe).withInputStream {  stream -> propsDe.load(stream)  }  propsEn.stringPropertyNames().each {  def deProperty = propsDe[it]  if (deProperty == null) {  println "Adding property $it to de locale"  propsDe.put(it, 'de_' + propsEn[it])  }  }  new File(propertyFileDe).withWriter {  propsDe.store(it, null)  }  println "locale files has been synced"
  32. Agenda Groovy for java developers Groovy as DSL Groovy for

    scripts development Some project build on goovy
  33. easyb given "an empty stack",{ stack = new Stack() }

    when "null is pushed", { pushnull = { stack.push(null) } } then "an exception should be thrown", { ensureThrows(RuntimeException){ pushnull() } } and "then the stack should still be empty", { stack.empty.shouldBe true }
  34. Geb import geb.Browser Browser.drive { go "http://myapp.com/login" assert $("h1").text() ==

    "Please Login" $("form.login").with { username = "admin" password = "password" login().click() } assert $("h1").text() == "Admin Section" }
  35. Groovy builder vs XML Browser.drive { to GoogleHomePage assert at(GoogleHomePage)

    search.field.value("wikipedia") waitFor { at GoogleResultsPage } assert firstResultLink.text() == "Wikipedia" firstResultLink.click() waitFor { at WikipediaPage } }
  36. Groovy builder vs XML  wizard {  title ua:

    "Тестовий візард", ru: "Тестовый визард"  info ua: "Цей візард призначений для тестування", ru: "Этот визард предназначен для тестирования"  steps "Step1": {  previousButton false  nextButton true  cancelButton true  finishButton false  title ua: "Перший крок", ru: "Первый шаг"  info ua: ''' На першому кроці нам нічого особливого не треба робити.  Він просто призначений для перевірки різних TextBox.''',  ru: ''' На первом шаге нам ничего особенного делать не надо.  Он просто предназначен для проверки разных TextBox.'''
  37. EasyB DSL before "initialize the queue for each spec", {

    queue = new Queue() } it "should dequeue gives item just enqueued", { queue.enqueue(2) queue.dequeue().shouldBe(2) } it "should throw an exception when null is enqueued", { ensureThrows(RuntimeException){ queue.enqueue(null) } }
  38. EasyB DSL before "initialize the queue for each spec", {

    queue = new Queue() } it "should dequeue gives item just enqueued", { queue.enqueue(2) queue.dequeue().shouldBe(2) } it "should throw an exception when null is enqueued", { ensureThrows(RuntimeException){ queue.enqueue(null) } }