SlideShare a Scribd company logo
1 of 85
Download to read offline
G*

JJUG CCC 2011 Spring
           @kiy0taka
※ kiy0taka 0
G*
Groovy?
HelloWorld.java

public class HelloWorld {
  public static void main(String[] args) {
    System.out.println("Hello, World!");
  }
}
HelloWorld.groovy

public class HelloWorld {
  public static void main(String[] args) {
    System.out.println("Hello, World!");
  }
}


    Java
HelloWorld.groovy

public class HelloWorld {
  public static void main(String[] args) {
    System.out.println("Hello, World!")
  }
}
HelloWorld.groovy

public class HelloWorld {
  public static void main(String[] args) {
    System.out.println "Hello, World!"
  }
}
HelloWorld.groovy

public static void main(String[] args) {
  System.out.println "Hello, World!"
}
HelloWorld.groovy


System.out.println "Hello, World!"




          main
HelloWorld.groovy


   println "Hello, World!"




   System.out.println → println
One-Liner


groovy -e "println 'Hello, World!'"
Java



 def file = new File("./hoge.txt")
def text = new File("./hoge.txt").text
Web



new URL('http://www.java-users.jp/contents/').getText('UTF-8')
String

println 'ls -la /opt/local'.execute().text

total 8
drwxr-xr-x    12   root    admin     408   11   23   19:32   .
drwxr-xr-x     3   root    admin     102   11    7   14:34   ..
drwxr-xr-x     5   root    wheel     170   11   24   13:02   Library
drwxr-xr-x   686   root    admin   23324   11   27   18:06   bin
drwxr-xr-x    25   root    admin     850   11   24   17:01   etc
drwxr-xr-x   177   root    admin    6018   11   24   17:01   include
drwxr-xr-x   988   root    admin   33592   11   24   17:01   lib
drwxr-xr-x    22   root    admin     748   11   24   16:17   libexec
lrwxr-xr-x     1   65534   wheel       9   11   23   18:42   man -> share/man
drwxr-xr-x     5   root    admin     170   11   24   13:37   sbin
drwxr-xr-x    76   root    admin    2584   11   27   18:06   share
drwxr-xr-x     8   root    admin     272   11   24   13:02   var
import

  import   java.lang
  import   java.math
  import   java.io
  import   java.net
  import   java.util
  import   groovy.lang
  import   groovy.util
Java


import org.apache.poi.hssf.usermodel.*

def workBook = new HSSFWorkbook(new File('./foo.xls')
workBook.newInputStream()).sheets.each { sheet ->
    sheet.firstRowNum.upto(sheet.lastRowNum) {
        sheet.getRow(it).with { row ->
            row.firstCellNum.upto(row.lastCellNum - 1) {
                println row.getCell(it).stringCellValue
            }
        }
    }
}
jar

@Grab('org.apache.poi:poi:3.2-FINAL')
import org.apache.poi.hssf.usermodel.*

def workBook = new HSSFWorkbook(new File('./foo.xls')
workBook.newInputStream()).sheets.each { sheet ->
    sheet.firstRowNum.upto(sheet.lastRowNum) {
        sheet.getRow(it).with { row ->
            row.firstCellNum.upto(row.lastCellNum - 1) {
                println row.getCell(it).stringCellValue
            }
        }
    }
}
Ant
 def ant = new AntBuilder()

 ant.unzip(src: 'xxx.zip', dest:'dest')

 ant.mail(mailhost:'hostname', subject:'hello',
   charset:'utf-8',
   user:user,
   password:password) {
     from address:'xxx@example.com'
     to address:'kiy0taka333@gmail.com'
     message 'Hello World!'
 }
// Groovy
$ time groovy -e "println 'Hello'"
Hello

real!0m1.292s
user!0m1.283s
sys! 0m0.192s


// GroovyServ
$ time groovyclient -e "println 'Hello'"
Hello

real!0m0.036s
user!0m0.001s
sys! 0m0.003s
Swing(Java)
                                                                       contentPane.add(button);
package sample;
                                                                       setDefaultCloseOperation(EXIT_ON_CLOSE);
import   java.awt.Container;                                           pack();
import   java.awt.GridLayout;                                          setVisible(true);
import   java.awt.event.ActionEvent;                               }
import   java.awt.event.ActionListener;
                                                                   public static void main(String[] args) {
import   javax.swing.JButton;                                          SwingUtilities.invokeLater(new Runnable() {
import   javax.swing.JFrame;                                               public void run() {
import   javax.swing.JLabel;                                                   new Hello();
import   javax.swing.JTextArea;                                            }
import   javax.swing.SwingUtilities;                                   });
                                                                   }
public class Hello extends JFrame {                            }

    public Hello() {
        super("Hello");

          Container contentPane = getContentPane();
          contentPane.setLayout(new GridLayout(3, 1));

          JLabel label = new JLabel("Label");
          contentPane.add(label);

          JTextArea textArea = new JTextArea("Text Area");
          textArea.setColumns(20);
          textArea.setRows(2);
          contentPane.add(textArea);

          JButton button = new JButton("Button");
          button.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent evt) {
                  ...
              }
          });
Groovy
import groovy.swing.SwingBuilder

new SwingBuilder().edt {
    frame(title:'Hello', show:true, pack:true) {
        gridLayout(cols:1, rows:3)
        label 'Label'
        textArea('Text Area', rows:2, columns:20)
        button('Button', actionPerformed:{ evt ->
            ...
        })
    }
}
SwingBuilder
import groovy.swing.SwingBuilder

new SwingBuilder().edt {
    frame(show:true, pack:true) {
        tableLayout {
            tr {
                 td { label 'UserName: ' }
                 td { textField columns:20 }
            }
            tr {
                 td { label 'Password: ' }
                 td { passwordField columns:20 }
            }
            tr {
                 td(colspan:2) { button 'Login' }
            }
        }
    }
}
https://gist.github.com/913279
h2console.groovy
@Grab('org.mortbay.jetty:jetty-embedded:6.1.25')
@Grab('com.h2database:h2:1.2.144')
@Grab('mysql:mysql-connector-java:5.1.13')
import org.mortbay.jetty.Server
import org.mortbay.jetty.servlet.Context
import org.h2.server.web.WebServlet

def server = new Server(8080)
new Context(server, "/", Context.SESSIONS)
  .addServlet(WebServlet, "/*")
server.start()



        https://gist.github.com/717932
please show the
square_root of 100
show = { println it }
square_root = { Math.sqrt(it) }

def please(action) {
  [the: { what ->
     [of: { n -> action(what(n)) }]
  }]
}

please(show).the(square_root).of(100)
show = { println it }
square_root = { Math.sqrt(it) }

def please(action) {
  [the: { what ->
     [of: { n -> action(what(n)) }]
  }]
}

please show the square_root of 100
Object.metaClass.     =
Object.metaClass.     =
{ clos -> clos(delegate) }

    = { it }
          = { println it }
     = { Math.sqrt(it) }

    100
import static groovyx.gpars.GParsPool.withPool

def list = [1, 2, 3, 4, 5]

withPool {
  def result = list.collectParallel { it * 2 }
  assert result == [2, 4, 6, 8, 10]
}
import groovy.json.*       def slurper = new JsonSlurper()
                           def json = slurper.parseText(text)

def text = '''[            assert json == [
  ["aaa", "bbb", "ccc"],     ["aaa", "bbb", "ccc"],
  {                          [
     "key1" : "value1",         "key1" : "value1",
     "key2" : "value2",         "key2" : "value2",
     "key3" : "value3",         "key3" : "value3",
     "key4" : ""                "key4" : ""
  },                         ],
  ["ddd", "eee", "fff"]      ["ddd", "eee", "fff"]
]                          ]
'''
import groovy.json.*

def json = new JsonBuilder()
json (
  ["aaa", "bbb", "ccc"],
  [
     "key1" : "value1",
     "key2" : "value2",
     "key3" : "value3",
     "key4" : ""
  ],
  ["ddd", "eee", "fff"]
)

println json
import org.gcontracts.annotations.*

@Invariant({ speed() >= 0 })
class Rocket {

    @Requires({ isStarted() })
    @Ensures({ old.speed < speed })
    def accelerate() { ... }

    boolean isStarted() { ... }
    def speed() { ... }

}
def plus2 = { it + 2 }
def times3 = { it * 3 }

def times3plus2 = plus2 << times3
assert times3plus2(3) == 11
assert times3plus2(4) == plus2(times3(4))

def plus2times3 = times3 << plus2
assert plus2times3(3) == 15
assert plus2times3(5) == times3(plus2(5))

assert times3plus2(3) == (times3 >> plus2)(3)
@Log
import groovy.util.logging.*

@Log
class Car {
     Car() {
         log.info 'Car constructed'
     }
}

def c = new Car()



  @Commons     @Log4j   @Slf4j
@Log    @Commons     @Log4j    @Slf4j
          @Field    @PackageScope
   @AutoClone      @AutoExternalizable
  @ThreadInterrupt      @TimedInterrupt
  @ConditionalInterrupt          @ToString
@EqualsAndHashCode      @TupleConstructor
  @Canonical       @InheritConstructors
    @WithReadLock      @WithWriteLock
               @ListenerList
Grails
create-app            generate-all
create-controller     generate-controller
create-domain-class   generate-views
create-script         package
create-service        run-app
create-tag-lib        run-war
create-unit-test      test-app
package myapp

class Message {

    String text

    static constraints = {
        text blank:false, maxSize:500
    }
}
package myapp

class MessageController {

    static scaffold = true
}
Gaelyk:Controller

 log.info "Setting attribute datetime"

 request.datetime = new Date().toString()

 log.info "Forwarding to the template"

 forward '/datetime.gtpl'
Gaelyk:View
<% include '/WEB-INF/includes/header.gtpl' %>

<h1>Date / time</h1>

<p>
       <% log.info "outputing the datetime attribute" %>
       The current date and time:
       ${request.datetime}
</p>

<% include '/WEB-INF/includes/footer.gtpl' %>
Gaelyk:Datastore

import com.google.appengine.api.datastore.Entity

def entity = new Entity("person")
entity.name = "Kiyotaka Oku"
entity.age = 31

entity.save()
datastore      blobstore
  memcache        oauth
  urlFetch      namespace
    mail       capabilities
   images        channel
   users          files
    user         backends
defaultQueue    lifecycle
   queues       localMode
    xmpp           app
Gaelyk:Datastore
import   com.google.appengine.api.datastore.*
import   static com.google.appengine.api.datastore.FetchOptions.Builder.*
import   static com.google.appengine.api.datastore.Query.FilterOperator.*
import   static com.google.appengine.api.datastore.Query.SortDirection.*

def query = new Query('person').with {
    addFilter 'age', GREATER_THAN_OR_EQUAL, 30
    addSort 'name', ASCENDING
}

def persons = datastore.prepare(query).asList(withLimit(21))
Gaelyk:Mail

mail.send sender: "kiy0taka333@gmail.com",
    to: "xxx@example.com",
    subject: "Hello",
    textBody: "Hello, how are you doing?"
Gaelyk:TaskQueue

defaultQueue << [
     countdownMillis: 1000, url: "/task/dailyEmail",
     taskName: "Send daily email newsletter",
     method: 'PUT', params: [date: '20090914'],
     payload: content
]
Griffon
Getting Started
$ griffon create-app myapp
$ cd myapp
$ griffon run-app
Griffon   MVC




MVC
Gradle
apply plugin: 'groovy'

repositories {
    mavenCentral()
}

dependencies {
    groovy 'org.codehaus.groovy:groovy:1.8.0'
    compile 'junit:junit:4.8.2'
}
$ gradle clean build
:clean
:compileJava
:compileGroovy
:processResources
:classes
:jar
:assemble
:compileTestJava
:compileTestGroovy
:processTestResources
:testClasses
:test
:check
:build

BUILD SUCCESSFUL

Total time: 13.766 secs
task checksum << {
    fileList('../antLoadfileResources').each {File file ->
        ant.checksum(file: file, property: "cs_$file.name")
        println "$file.name Checksum: ${ant.properties["cs_$file.name"]}"
    }
}

task loadfile << {
    fileList('../antLoadfileResources').each {File file ->
        ant.loadfile(srcFile: file, property: file.name)
        println "I'm fond of $file.name"
    }
}

File[] fileList(String dir) {
    file(dir).listFiles({file -> file.isFile() } as FileFilter).sort()
}
G*Magazine
G*
Groovy and Java Comparison for Beginners

More Related Content

What's hot

Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksMongoDB
 
The Ring programming language version 1.5.4 book - Part 40 of 185
The Ring programming language version 1.5.4 book - Part 40 of 185The Ring programming language version 1.5.4 book - Part 40 of 185
The Ring programming language version 1.5.4 book - Part 40 of 185Mahmoud Samir Fayed
 
Wprowadzenie do technologi Big Data i Apache Hadoop
Wprowadzenie do technologi Big Data i Apache HadoopWprowadzenie do technologi Big Data i Apache Hadoop
Wprowadzenie do technologi Big Data i Apache HadoopSages
 
The Ring programming language version 1.7 book - Part 72 of 196
The Ring programming language version 1.7 book - Part 72 of 196The Ring programming language version 1.7 book - Part 72 of 196
The Ring programming language version 1.7 book - Part 72 of 196Mahmoud Samir Fayed
 
外部環境への依存をテストする
外部環境への依存をテストする外部環境への依存をテストする
外部環境への依存をテストするShunsuke Maeda
 
Mysql5.1 character set testing
Mysql5.1 character set testingMysql5.1 character set testing
Mysql5.1 character set testingPhilip Zhong
 
Mysql handle socket
Mysql handle socketMysql handle socket
Mysql handle socketPhilip Zhong
 
Compare mysql5.1.50 mysql5.5.8
Compare mysql5.1.50 mysql5.5.8Compare mysql5.1.50 mysql5.5.8
Compare mysql5.1.50 mysql5.5.8Philip Zhong
 
Greach, GroovyFx Workshop
Greach, GroovyFx WorkshopGreach, GroovyFx Workshop
Greach, GroovyFx WorkshopDierk König
 
The Ring programming language version 1.5.1 book - Part 12 of 180
The Ring programming language version 1.5.1 book - Part 12 of 180The Ring programming language version 1.5.1 book - Part 12 of 180
The Ring programming language version 1.5.1 book - Part 12 of 180Mahmoud Samir Fayed
 
Kamil Chmielewski, Jacek Juraszek - "Hadoop. W poszukiwaniu złotego młotka."
Kamil Chmielewski, Jacek Juraszek - "Hadoop. W poszukiwaniu złotego młotka."Kamil Chmielewski, Jacek Juraszek - "Hadoop. W poszukiwaniu złotego młotka."
Kamil Chmielewski, Jacek Juraszek - "Hadoop. W poszukiwaniu złotego młotka."sjabs
 
The Ring programming language version 1.8 book - Part 74 of 202
The Ring programming language version 1.8 book - Part 74 of 202The Ring programming language version 1.8 book - Part 74 of 202
The Ring programming language version 1.8 book - Part 74 of 202Mahmoud Samir Fayed
 
Java libraries you can't afford to miss
Java libraries you can't afford to missJava libraries you can't afford to miss
Java libraries you can't afford to missAndres Almiray
 
The Ring programming language version 1.6 book - Part 71 of 189
The Ring programming language version 1.6 book - Part 71 of 189The Ring programming language version 1.6 book - Part 71 of 189
The Ring programming language version 1.6 book - Part 71 of 189Mahmoud Samir Fayed
 
QA Fest 2019. Saar Rachamim. Developing Tools, While Testing
QA Fest 2019. Saar Rachamim. Developing Tools, While TestingQA Fest 2019. Saar Rachamim. Developing Tools, While Testing
QA Fest 2019. Saar Rachamim. Developing Tools, While TestingQAFest
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleThierry Wasylczenko
 
Spock: A Highly Logical Way To Test
Spock: A Highly Logical Way To TestSpock: A Highly Logical Way To Test
Spock: A Highly Logical Way To TestHoward Lewis Ship
 

What's hot (20)

Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New Tricks
 
The Ring programming language version 1.5.4 book - Part 40 of 185
The Ring programming language version 1.5.4 book - Part 40 of 185The Ring programming language version 1.5.4 book - Part 40 of 185
The Ring programming language version 1.5.4 book - Part 40 of 185
 
Wprowadzenie do technologi Big Data i Apache Hadoop
Wprowadzenie do technologi Big Data i Apache HadoopWprowadzenie do technologi Big Data i Apache Hadoop
Wprowadzenie do technologi Big Data i Apache Hadoop
 
The Ring programming language version 1.7 book - Part 72 of 196
The Ring programming language version 1.7 book - Part 72 of 196The Ring programming language version 1.7 book - Part 72 of 196
The Ring programming language version 1.7 book - Part 72 of 196
 
外部環境への依存をテストする
外部環境への依存をテストする外部環境への依存をテストする
外部環境への依存をテストする
 
Spock and Geb in Action
Spock and Geb in ActionSpock and Geb in Action
Spock and Geb in Action
 
Mysql5.1 character set testing
Mysql5.1 character set testingMysql5.1 character set testing
Mysql5.1 character set testing
 
Mysql handle socket
Mysql handle socketMysql handle socket
Mysql handle socket
 
Compare mysql5.1.50 mysql5.5.8
Compare mysql5.1.50 mysql5.5.8Compare mysql5.1.50 mysql5.5.8
Compare mysql5.1.50 mysql5.5.8
 
Greach, GroovyFx Workshop
Greach, GroovyFx WorkshopGreach, GroovyFx Workshop
Greach, GroovyFx Workshop
 
The Ring programming language version 1.5.1 book - Part 12 of 180
The Ring programming language version 1.5.1 book - Part 12 of 180The Ring programming language version 1.5.1 book - Part 12 of 180
The Ring programming language version 1.5.1 book - Part 12 of 180
 
Kamil Chmielewski, Jacek Juraszek - "Hadoop. W poszukiwaniu złotego młotka."
Kamil Chmielewski, Jacek Juraszek - "Hadoop. W poszukiwaniu złotego młotka."Kamil Chmielewski, Jacek Juraszek - "Hadoop. W poszukiwaniu złotego młotka."
Kamil Chmielewski, Jacek Juraszek - "Hadoop. W poszukiwaniu złotego młotka."
 
The Ring programming language version 1.8 book - Part 74 of 202
The Ring programming language version 1.8 book - Part 74 of 202The Ring programming language version 1.8 book - Part 74 of 202
The Ring programming language version 1.8 book - Part 74 of 202
 
Java libraries you can't afford to miss
Java libraries you can't afford to missJava libraries you can't afford to miss
Java libraries you can't afford to miss
 
The Ring programming language version 1.6 book - Part 71 of 189
The Ring programming language version 1.6 book - Part 71 of 189The Ring programming language version 1.6 book - Part 71 of 189
The Ring programming language version 1.6 book - Part 71 of 189
 
QA Fest 2019. Saar Rachamim. Developing Tools, While Testing
QA Fest 2019. Saar Rachamim. Developing Tools, While TestingQA Fest 2019. Saar Rachamim. Developing Tools, While Testing
QA Fest 2019. Saar Rachamim. Developing Tools, While Testing
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradle
 
Introduction kot iin
Introduction kot iinIntroduction kot iin
Introduction kot iin
 
Spock: A Highly Logical Way To Test
Spock: A Highly Logical Way To TestSpock: A Highly Logical Way To Test
Spock: A Highly Logical Way To Test
 
#JavaFX.forReal() - ElsassJUG
#JavaFX.forReal() - ElsassJUG#JavaFX.forReal() - ElsassJUG
#JavaFX.forReal() - ElsassJUG
 

Viewers also liked

クラウドを支えるハードウェア・ソフトウェア基盤技術
クラウドを支えるハードウェア・ソフトウェア基盤技術クラウドを支えるハードウェア・ソフトウェア基盤技術
クラウドを支えるハードウェア・ソフトウェア基盤技術Ryousei Takano
 
BaseScriptについて
BaseScriptについてBaseScriptについて
BaseScriptについてKiyotaka Oku
 
AWS SDK for Haskell開発
AWS SDK for Haskell開発AWS SDK for Haskell開発
AWS SDK for Haskell開発Nomura Yusuke
 
独りガラパゴス開発
独りガラパゴス開発独りガラパゴス開発
独りガラパゴス開発道化師 堂華
 
エラーハンドリングモデル考察
エラーハンドリングモデル考察エラーハンドリングモデル考察
エラーハンドリングモデル考察道化師 堂華
 
C++ AMPを使ってみよう
C++ AMPを使ってみようC++ AMPを使ってみよう
C++ AMPを使ってみようOsamu Masutani
 
ソフトウェアエンジニアとして心がけてきたこと
ソフトウェアエンジニアとして心がけてきたことソフトウェアエンジニアとして心がけてきたこと
ソフトウェアエンジニアとして心がけてきたことyoshikishibata
 
ゲームアプリの数学@プログラマのための数学勉強会
ゲームアプリの数学@プログラマのための数学勉強会ゲームアプリの数学@プログラマのための数学勉強会
ゲームアプリの数学@プログラマのための数学勉強会Ryuichi Kubuki
 
今日から始めるGopher - スタートGo #0 @GDG名古屋
今日から始めるGopher - スタートGo #0 @GDG名古屋今日から始めるGopher - スタートGo #0 @GDG名古屋
今日から始めるGopher - スタートGo #0 @GDG名古屋Takuya Ueda
 
Macro in Scala
Macro in ScalaMacro in Scala
Macro in Scalatakezoe
 
Jbossとtomcatの性能を比べてみた
Jbossとtomcatの性能を比べてみたJbossとtomcatの性能を比べてみた
Jbossとtomcatの性能を比べてみたYuki Obara
 
ビズリーチの新サービスをScalaで作ってみた 〜マイクロサービスの裏側 #jissenscala
ビズリーチの新サービスをScalaで作ってみた 〜マイクロサービスの裏側 #jissenscalaビズリーチの新サービスをScalaで作ってみた 〜マイクロサービスの裏側 #jissenscala
ビズリーチの新サービスをScalaで作ってみた 〜マイクロサービスの裏側 #jissenscalatakezoe
 
Scala Frameworks for Web Application 2016
Scala Frameworks for Web Application 2016Scala Frameworks for Web Application 2016
Scala Frameworks for Web Application 2016takezoe
 

Viewers also liked (17)

クラウドを支えるハードウェア・ソフトウェア基盤技術
クラウドを支えるハードウェア・ソフトウェア基盤技術クラウドを支えるハードウェア・ソフトウェア基盤技術
クラウドを支えるハードウェア・ソフトウェア基盤技術
 
BaseScriptについて
BaseScriptについてBaseScriptについて
BaseScriptについて
 
AWS SDK for Haskell開発
AWS SDK for Haskell開発AWS SDK for Haskell開発
AWS SDK for Haskell開発
 
Doc and Error Handling
Doc and Error HandlingDoc and Error Handling
Doc and Error Handling
 
Hacking Robotics
Hacking RoboticsHacking Robotics
Hacking Robotics
 
独りガラパゴス開発
独りガラパゴス開発独りガラパゴス開発
独りガラパゴス開発
 
javafx-mini4wd
javafx-mini4wdjavafx-mini4wd
javafx-mini4wd
 
エラーハンドリングモデル考察
エラーハンドリングモデル考察エラーハンドリングモデル考察
エラーハンドリングモデル考察
 
C++ AMPを使ってみよう
C++ AMPを使ってみようC++ AMPを使ってみよう
C++ AMPを使ってみよう
 
ソフトウェアエンジニアとして心がけてきたこと
ソフトウェアエンジニアとして心がけてきたことソフトウェアエンジニアとして心がけてきたこと
ソフトウェアエンジニアとして心がけてきたこと
 
ゲームアプリの数学@プログラマのための数学勉強会
ゲームアプリの数学@プログラマのための数学勉強会ゲームアプリの数学@プログラマのための数学勉強会
ゲームアプリの数学@プログラマのための数学勉強会
 
今日から始めるGopher - スタートGo #0 @GDG名古屋
今日から始めるGopher - スタートGo #0 @GDG名古屋今日から始めるGopher - スタートGo #0 @GDG名古屋
今日から始めるGopher - スタートGo #0 @GDG名古屋
 
Macro in Scala
Macro in ScalaMacro in Scala
Macro in Scala
 
Jbossとtomcatの性能を比べてみた
Jbossとtomcatの性能を比べてみたJbossとtomcatの性能を比べてみた
Jbossとtomcatの性能を比べてみた
 
ビズリーチの新サービスをScalaで作ってみた 〜マイクロサービスの裏側 #jissenscala
ビズリーチの新サービスをScalaで作ってみた 〜マイクロサービスの裏側 #jissenscalaビズリーチの新サービスをScalaで作ってみた 〜マイクロサービスの裏側 #jissenscala
ビズリーチの新サービスをScalaで作ってみた 〜マイクロサービスの裏側 #jissenscala
 
Scala Frameworks for Web Application 2016
Scala Frameworks for Web Application 2016Scala Frameworks for Web Application 2016
Scala Frameworks for Web Application 2016
 
C++ tips4 cv修飾編
C++ tips4 cv修飾編C++ tips4 cv修飾編
C++ tips4 cv修飾編
 

Similar to Groovy and Java Comparison for Beginners

Jenkins and Groovy
Jenkins and GroovyJenkins and Groovy
Jenkins and GroovyKiyotaka Oku
 
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Tsuyoshi Yamamoto
 
Hibernate Import.Sql I18n
Hibernate Import.Sql I18nHibernate Import.Sql I18n
Hibernate Import.Sql I18nyifi2009
 
お題でGroovyプログラミング: Part A
お題でGroovyプログラミング: Part Aお題でGroovyプログラミング: Part A
お題でGroovyプログラミング: Part AKazuchika Sekiya
 
A topology of memory leaks on the JVM
A topology of memory leaks on the JVMA topology of memory leaks on the JVM
A topology of memory leaks on the JVMRafael Winterhalter
 
code for quiz in my sql
code for quiz  in my sql code for quiz  in my sql
code for quiz in my sql JOYITAKUNDU1
 
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
名古屋SGGAE/J勉強会 Grails、GaelykでハンズオンTsuyoshi Yamamoto
 
How to Clone Flappy Bird in Swift
How to Clone Flappy Bird in SwiftHow to Clone Flappy Bird in Swift
How to Clone Flappy Bird in SwiftGiordano Scalzo
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
Ejemplo radio
Ejemplo radioEjemplo radio
Ejemplo radiolupe ga
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with ClojureDmitry Buzdin
 
Making Java more dynamic: runtime code generation for the JVM
Making Java more dynamic: runtime code generation for the JVMMaking Java more dynamic: runtime code generation for the JVM
Making Java more dynamic: runtime code generation for the JVMRafael Winterhalter
 

Similar to Groovy and Java Comparison for Beginners (20)

Griffon @ Svwjug
Griffon @ SvwjugGriffon @ Svwjug
Griffon @ Svwjug
 
Jenkins and Groovy
Jenkins and GroovyJenkins and Groovy
Jenkins and Groovy
 
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
 
Hibernate Import.Sql I18n
Hibernate Import.Sql I18nHibernate Import.Sql I18n
Hibernate Import.Sql I18n
 
ES6 Overview
ES6 OverviewES6 Overview
ES6 Overview
 
お題でGroovyプログラミング: Part A
お題でGroovyプログラミング: Part Aお題でGroovyプログラミング: Part A
お題でGroovyプログラミング: Part A
 
A topology of memory leaks on the JVM
A topology of memory leaks on the JVMA topology of memory leaks on the JVM
A topology of memory leaks on the JVM
 
GroovyConsole2
GroovyConsole2GroovyConsole2
GroovyConsole2
 
code for quiz in my sql
code for quiz  in my sql code for quiz  in my sql
code for quiz in my sql
 
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
 
How to Clone Flappy Bird in Swift
How to Clone Flappy Bird in SwiftHow to Clone Flappy Bird in Swift
How to Clone Flappy Bird in Swift
 
Introduction to Groovy
Introduction to GroovyIntroduction to Groovy
Introduction to Groovy
 
V8
V8V8
V8
 
Easy Button
Easy ButtonEasy Button
Easy Button
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
Server1
Server1Server1
Server1
 
Jersey Guice AOP
Jersey Guice AOPJersey Guice AOP
Jersey Guice AOP
 
Ejemplo radio
Ejemplo radioEjemplo radio
Ejemplo radio
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
Making Java more dynamic: runtime code generation for the JVM
Making Java more dynamic: runtime code generation for the JVMMaking Java more dynamic: runtime code generation for the JVM
Making Java more dynamic: runtime code generation for the JVM
 

More from Kiyotaka Oku

Osaka Venture Meetup #3
Osaka Venture Meetup #3Osaka Venture Meetup #3
Osaka Venture Meetup #3Kiyotaka Oku
 
巨大不明ビルドの継続的統合を目的とするビルドパイプラインを主軸とした作戦要綱
巨大不明ビルドの継続的統合を目的とするビルドパイプラインを主軸とした作戦要綱巨大不明ビルドの継続的統合を目的とするビルドパイプラインを主軸とした作戦要綱
巨大不明ビルドの継続的統合を目的とするビルドパイプラインを主軸とした作戦要綱Kiyotaka Oku
 
ミニ四駆ジャパンカップで勝つ方法を考える
ミニ四駆ジャパンカップで勝つ方法を考えるミニ四駆ジャパンカップで勝つ方法を考える
ミニ四駆ジャパンカップで勝つ方法を考えるKiyotaka Oku
 
Jenkins plugin memo
Jenkins plugin memoJenkins plugin memo
Jenkins plugin memoKiyotaka Oku
 
GDK48総選挙の裏側
GDK48総選挙の裏側GDK48総選挙の裏側
GDK48総選挙の裏側Kiyotaka Oku
 
Grails/Groovyによる開発事例紹介
Grails/Groovyによる開発事例紹介Grails/Groovyによる開発事例紹介
Grails/Groovyによる開発事例紹介Kiyotaka Oku
 
Griffon不定期便〜G*ワークショップ編〜
Griffon不定期便〜G*ワークショップ編〜Griffon不定期便〜G*ワークショップ編〜
Griffon不定期便〜G*ワークショップ編〜Kiyotaka Oku
 
日本Grails/Groovyユーザーグループ
日本Grails/Groovyユーザーグループ日本Grails/Groovyユーザーグループ
日本Grails/GroovyユーザーグループKiyotaka Oku
 
Jenkinsプラグインの作り方
Jenkinsプラグインの作り方Jenkinsプラグインの作り方
Jenkinsプラグインの作り方Kiyotaka Oku
 
とある断片の超動的言語
とある断片の超動的言語とある断片の超動的言語
とある断片の超動的言語Kiyotaka Oku
 
Groovy and-hudson2
Groovy and-hudson2Groovy and-hudson2
Groovy and-hudson2Kiyotaka Oku
 

More from Kiyotaka Oku (20)

Osaka Venture Meetup #3
Osaka Venture Meetup #3Osaka Venture Meetup #3
Osaka Venture Meetup #3
 
巨大不明ビルドの継続的統合を目的とするビルドパイプラインを主軸とした作戦要綱
巨大不明ビルドの継続的統合を目的とするビルドパイプラインを主軸とした作戦要綱巨大不明ビルドの継続的統合を目的とするビルドパイプラインを主軸とした作戦要綱
巨大不明ビルドの継続的統合を目的とするビルドパイプラインを主軸とした作戦要綱
 
ミニ四駆ジャパンカップで勝つ方法を考える
ミニ四駆ジャパンカップで勝つ方法を考えるミニ四駆ジャパンカップで勝つ方法を考える
ミニ四駆ジャパンカップで勝つ方法を考える
 
Jenkins plugin memo
Jenkins plugin memoJenkins plugin memo
Jenkins plugin memo
 
Spockの基礎
Spockの基礎Spockの基礎
Spockの基礎
 
JUC2012
JUC2012JUC2012
JUC2012
 
GDK48総選挙の裏側
GDK48総選挙の裏側GDK48総選挙の裏側
GDK48総選挙の裏側
 
Jenkins入門
Jenkins入門Jenkins入門
Jenkins入門
 
Grails/Groovyによる開発事例紹介
Grails/Groovyによる開発事例紹介Grails/Groovyによる開発事例紹介
Grails/Groovyによる開発事例紹介
 
Griffon不定期便〜G*ワークショップ編〜
Griffon不定期便〜G*ワークショップ編〜Griffon不定期便〜G*ワークショップ編〜
Griffon不定期便〜G*ワークショップ編〜
 
日本Grails/Groovyユーザーグループ
日本Grails/Groovyユーザーグループ日本Grails/Groovyユーザーグループ
日本Grails/Groovyユーザーグループ
 
GroovyConsole
GroovyConsoleGroovyConsole
GroovyConsole
 
Jenkinsプラグインの作り方
Jenkinsプラグインの作り方Jenkinsプラグインの作り方
Jenkinsプラグインの作り方
 
Devsumi Openjam
Devsumi OpenjamDevsumi Openjam
Devsumi Openjam
 
とある断片の超動的言語
とある断片の超動的言語とある断片の超動的言語
とある断片の超動的言語
 
Mote Hudson
Mote HudsonMote Hudson
Mote Hudson
 
Groovy and-hudson2
Groovy and-hudson2Groovy and-hudson2
Groovy and-hudson2
 
Gaelyk
GaelykGaelyk
Gaelyk
 
JDO
JDOJDO
JDO
 
Grails on GAE/J
Grails on GAE/JGrails on GAE/J
Grails on GAE/J
 

Recently uploaded

From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 

Recently uploaded (20)

From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 

Groovy and Java Comparison for Beginners

  • 1. G* JJUG CCC 2011 Spring @kiy0taka
  • 3. G*
  • 5. HelloWorld.java public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); } }
  • 6. HelloWorld.groovy public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); } } Java
  • 7. HelloWorld.groovy public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!") } }
  • 8. HelloWorld.groovy public class HelloWorld { public static void main(String[] args) { System.out.println "Hello, World!" } }
  • 9. HelloWorld.groovy public static void main(String[] args) { System.out.println "Hello, World!" }
  • 11. HelloWorld.groovy println "Hello, World!" System.out.println → println
  • 12. One-Liner groovy -e "println 'Hello, World!'"
  • 13.
  • 14. Java def file = new File("./hoge.txt")
  • 15. def text = new File("./hoge.txt").text
  • 17. String println 'ls -la /opt/local'.execute().text total 8 drwxr-xr-x 12 root admin 408 11 23 19:32 . drwxr-xr-x 3 root admin 102 11 7 14:34 .. drwxr-xr-x 5 root wheel 170 11 24 13:02 Library drwxr-xr-x 686 root admin 23324 11 27 18:06 bin drwxr-xr-x 25 root admin 850 11 24 17:01 etc drwxr-xr-x 177 root admin 6018 11 24 17:01 include drwxr-xr-x 988 root admin 33592 11 24 17:01 lib drwxr-xr-x 22 root admin 748 11 24 16:17 libexec lrwxr-xr-x 1 65534 wheel 9 11 23 18:42 man -> share/man drwxr-xr-x 5 root admin 170 11 24 13:37 sbin drwxr-xr-x 76 root admin 2584 11 27 18:06 share drwxr-xr-x 8 root admin 272 11 24 13:02 var
  • 18. import import java.lang import java.math import java.io import java.net import java.util import groovy.lang import groovy.util
  • 19. Java import org.apache.poi.hssf.usermodel.* def workBook = new HSSFWorkbook(new File('./foo.xls') workBook.newInputStream()).sheets.each { sheet -> sheet.firstRowNum.upto(sheet.lastRowNum) { sheet.getRow(it).with { row -> row.firstCellNum.upto(row.lastCellNum - 1) { println row.getCell(it).stringCellValue } } } }
  • 20. jar @Grab('org.apache.poi:poi:3.2-FINAL') import org.apache.poi.hssf.usermodel.* def workBook = new HSSFWorkbook(new File('./foo.xls') workBook.newInputStream()).sheets.each { sheet -> sheet.firstRowNum.upto(sheet.lastRowNum) { sheet.getRow(it).with { row -> row.firstCellNum.upto(row.lastCellNum - 1) { println row.getCell(it).stringCellValue } } } }
  • 21. Ant def ant = new AntBuilder() ant.unzip(src: 'xxx.zip', dest:'dest') ant.mail(mailhost:'hostname', subject:'hello', charset:'utf-8', user:user, password:password) { from address:'xxx@example.com' to address:'kiy0taka333@gmail.com' message 'Hello World!' }
  • 22.
  • 23.
  • 24. // Groovy $ time groovy -e "println 'Hello'" Hello real!0m1.292s user!0m1.283s sys! 0m0.192s // GroovyServ $ time groovyclient -e "println 'Hello'" Hello real!0m0.036s user!0m0.001s sys! 0m0.003s
  • 25.
  • 26. Swing(Java) contentPane.add(button); package sample; setDefaultCloseOperation(EXIT_ON_CLOSE); import java.awt.Container; pack(); import java.awt.GridLayout; setVisible(true); import java.awt.event.ActionEvent; } import java.awt.event.ActionListener; public static void main(String[] args) { import javax.swing.JButton; SwingUtilities.invokeLater(new Runnable() { import javax.swing.JFrame; public void run() { import javax.swing.JLabel; new Hello(); import javax.swing.JTextArea; } import javax.swing.SwingUtilities; }); } public class Hello extends JFrame { } public Hello() { super("Hello"); Container contentPane = getContentPane(); contentPane.setLayout(new GridLayout(3, 1)); JLabel label = new JLabel("Label"); contentPane.add(label); JTextArea textArea = new JTextArea("Text Area"); textArea.setColumns(20); textArea.setRows(2); contentPane.add(textArea); JButton button = new JButton("Button"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { ... } });
  • 27. Groovy import groovy.swing.SwingBuilder new SwingBuilder().edt { frame(title:'Hello', show:true, pack:true) { gridLayout(cols:1, rows:3) label 'Label' textArea('Text Area', rows:2, columns:20) button('Button', actionPerformed:{ evt -> ... }) } }
  • 28. SwingBuilder import groovy.swing.SwingBuilder new SwingBuilder().edt { frame(show:true, pack:true) { tableLayout { tr { td { label 'UserName: ' } td { textField columns:20 } } tr { td { label 'Password: ' } td { passwordField columns:20 } } tr { td(colspan:2) { button 'Login' } } } } }
  • 30.
  • 31. h2console.groovy @Grab('org.mortbay.jetty:jetty-embedded:6.1.25') @Grab('com.h2database:h2:1.2.144') @Grab('mysql:mysql-connector-java:5.1.13') import org.mortbay.jetty.Server import org.mortbay.jetty.servlet.Context import org.h2.server.web.WebServlet def server = new Server(8080) new Context(server, "/", Context.SESSIONS) .addServlet(WebServlet, "/*") server.start() https://gist.github.com/717932
  • 32.
  • 34. show = { println it } square_root = { Math.sqrt(it) } def please(action) { [the: { what -> [of: { n -> action(what(n)) }] }] } please(show).the(square_root).of(100)
  • 35. show = { println it } square_root = { Math.sqrt(it) } def please(action) { [the: { what -> [of: { n -> action(what(n)) }] }] } please show the square_root of 100
  • 36. Object.metaClass. = Object.metaClass. = { clos -> clos(delegate) } = { it } = { println it } = { Math.sqrt(it) } 100
  • 37.
  • 38.
  • 39. import static groovyx.gpars.GParsPool.withPool def list = [1, 2, 3, 4, 5] withPool { def result = list.collectParallel { it * 2 } assert result == [2, 4, 6, 8, 10] }
  • 40.
  • 41. import groovy.json.* def slurper = new JsonSlurper() def json = slurper.parseText(text) def text = '''[ assert json == [ ["aaa", "bbb", "ccc"], ["aaa", "bbb", "ccc"], { [ "key1" : "value1", "key1" : "value1", "key2" : "value2", "key2" : "value2", "key3" : "value3", "key3" : "value3", "key4" : "" "key4" : "" }, ], ["ddd", "eee", "fff"] ["ddd", "eee", "fff"] ] ] '''
  • 42. import groovy.json.* def json = new JsonBuilder() json ( ["aaa", "bbb", "ccc"], [ "key1" : "value1", "key2" : "value2", "key3" : "value3", "key4" : "" ], ["ddd", "eee", "fff"] ) println json
  • 43.
  • 44. import org.gcontracts.annotations.* @Invariant({ speed() >= 0 }) class Rocket { @Requires({ isStarted() }) @Ensures({ old.speed < speed }) def accelerate() { ... } boolean isStarted() { ... } def speed() { ... } }
  • 45. def plus2 = { it + 2 } def times3 = { it * 3 } def times3plus2 = plus2 << times3 assert times3plus2(3) == 11 assert times3plus2(4) == plus2(times3(4)) def plus2times3 = times3 << plus2 assert plus2times3(3) == 15 assert plus2times3(5) == times3(plus2(5)) assert times3plus2(3) == (times3 >> plus2)(3)
  • 46.
  • 47.
  • 48. @Log import groovy.util.logging.* @Log class Car { Car() { log.info 'Car constructed' } } def c = new Car() @Commons @Log4j @Slf4j
  • 49. @Log @Commons @Log4j @Slf4j @Field @PackageScope @AutoClone @AutoExternalizable @ThreadInterrupt @TimedInterrupt @ConditionalInterrupt @ToString @EqualsAndHashCode @TupleConstructor @Canonical @InheritConstructors @WithReadLock @WithWriteLock @ListenerList
  • 50.
  • 52. create-app generate-all create-controller generate-controller create-domain-class generate-views create-script package create-service run-app create-tag-lib run-war create-unit-test test-app
  • 53.
  • 54. package myapp class Message { String text static constraints = { text blank:false, maxSize:500 } }
  • 55. package myapp class MessageController { static scaffold = true }
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63. Gaelyk:Controller log.info "Setting attribute datetime" request.datetime = new Date().toString() log.info "Forwarding to the template" forward '/datetime.gtpl'
  • 64. Gaelyk:View <% include '/WEB-INF/includes/header.gtpl' %> <h1>Date / time</h1> <p> <% log.info "outputing the datetime attribute" %> The current date and time: ${request.datetime} </p> <% include '/WEB-INF/includes/footer.gtpl' %>
  • 65. Gaelyk:Datastore import com.google.appengine.api.datastore.Entity def entity = new Entity("person") entity.name = "Kiyotaka Oku" entity.age = 31 entity.save()
  • 66. datastore blobstore memcache oauth urlFetch namespace mail capabilities images channel users files user backends defaultQueue lifecycle queues localMode xmpp app
  • 67. Gaelyk:Datastore import com.google.appengine.api.datastore.* import static com.google.appengine.api.datastore.FetchOptions.Builder.* import static com.google.appengine.api.datastore.Query.FilterOperator.* import static com.google.appengine.api.datastore.Query.SortDirection.* def query = new Query('person').with { addFilter 'age', GREATER_THAN_OR_EQUAL, 30 addSort 'name', ASCENDING } def persons = datastore.prepare(query).asList(withLimit(21))
  • 68. Gaelyk:Mail mail.send sender: "kiy0taka333@gmail.com", to: "xxx@example.com", subject: "Hello", textBody: "Hello, how are you doing?"
  • 69. Gaelyk:TaskQueue defaultQueue << [ countdownMillis: 1000, url: "/task/dailyEmail", taskName: "Send daily email newsletter", method: 'PUT', params: [date: '20090914'], payload: content ]
  • 70.
  • 72. Getting Started $ griffon create-app myapp $ cd myapp $ griffon run-app
  • 73. Griffon MVC MVC
  • 74.
  • 75.
  • 76.
  • 78. apply plugin: 'groovy' repositories { mavenCentral() } dependencies { groovy 'org.codehaus.groovy:groovy:1.8.0' compile 'junit:junit:4.8.2' }
  • 79. $ gradle clean build :clean :compileJava :compileGroovy :processResources :classes :jar :assemble :compileTestJava :compileTestGroovy :processTestResources :testClasses :test :check :build BUILD SUCCESSFUL Total time: 13.766 secs
  • 80. task checksum << { fileList('../antLoadfileResources').each {File file -> ant.checksum(file: file, property: "cs_$file.name") println "$file.name Checksum: ${ant.properties["cs_$file.name"]}" } } task loadfile << { fileList('../antLoadfileResources').each {File file -> ant.loadfile(srcFile: file, property: file.name) println "I'm fond of $file.name" } } File[] fileList(String dir) { file(dir).listFiles({file -> file.isFile() } as FileFilter).sort() }
  • 81.
  • 82.
  • 84. G*