• Save
Introduction To Groovy 2005
Upcoming SlideShare
Loading in...5
×
 

Introduction To Groovy 2005

on

  • 3,148 views

A quick introduction to Groovy and Grails made in 2005 to Oracle Consulting folks

A quick introduction to Groovy and Grails made in 2005 to Oracle Consulting folks

Statistics

Views

Total Views
3,148
Views on SlideShare
3,147
Embed Views
1

Actions

Likes
2
Downloads
0
Comments
0

1 Embed 1

http://www.slideshare.net 1

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Introduction To Groovy 2005 Introduction To Groovy 2005 Presentation Transcript

  •  
  • Introduction to Dynamic Languages
    • Tugdual Grall
    • Oracle Application Server
    • Product Management
  • Simple Example
    • public class FilterApp {
    • public static void main(String[] args) {
    • List<String> list = new ArrayList();
    • list.add(&quot;Olaf&quot;); list.add(&quot;Tug&quot;); list.add(&quot;John&quot;); list.add(&quot;Dave&quot;);
    • FilterApp filter = new FilterApp();
    • List<String> data = filter.filterLongerThan(list,4);
    • System.out.println(data.size());
    • Iterator it = data.iterator();
    • while (it.hasNext()) {System.out.println(it.next());}
    • }
    • public List filterLongerThan(List list, int length) {
    • List<String> result = new ArrayList();
    • Iterator it = list.iterator();
    • while (it.hasNext()) {
    • String item = (String)it.next();
    • if (item.length()>= length) {result.add(item);}
    • }
    • return result;
    • }
    • }
  • Simple Example
    • def list = [&quot;Olaf&quot;,&quot;Tug&quot;,&quot;John&quot;,&quot;Dave&quot;]
    • def data = list.findAll { it.size() >= 4 }
    • println data.size()
    • data.each { println it }
    Java 25-30 Lines / Groovy 4 lines
  • Why Scripting?
    • Scripting languages are in fashion (again?)
      • AJAX with JavaScript™ technology, and Ruby on
      • Rails with Ruby
    • Java SE 6 integrates JSR 223 with Rhino
    • JCP agreed to standardize Groovy (JSR 241) and BeanShell (JSR 274)
    • Upcoming bytecode invokeDynamic (JSR 292)
    • Microsoft also believe in dynamic languages and hire IronPython lead
    • Need simplicity to overcome enterprise development complexity
  • Three Main Use Cases of Integration
    • Prototyping/testing/scripting
      • Shell or build scripting, data manipulation, unit testing, code generation, driving native applications
    • Building standalone applications
      • Small to mid-sized non-critical applications
    • Integrating scripting in Java EE applications
      • Programmatic configuration (less XML)
      • Business rules externalization
      • UI or application customizations
  • Java Technology & Scripting
    • Leverage Java Platform
      • Use scripts inside Java SE and Java EE
      • Reuse existing Java technology skills and components
    • Many existing languages on the Java VM
      • Groovy, Rhino (JavaScript), BeanShell, Jython, JRuby, Pnuts, Scala…
    • Current standardization effort around scripting languages and Java technology
      • JSR 223, JSR 241, JSR 274, JSR 292
    • Let’s dive in Groovy as an example…
  • Why Groovy Is Relevant?
    • Groovy is a dynamic and agile scripting language for the Java VM
    • OSS project hosted by Codehaus
    • Inspired by Ruby,Python and SmallTalk
    • Generates bytecode for the Java VM: integrates well with Java libraries
    • However, Groovy differentiates itself
      • GDK: additional libraries to simplify complex APIs
      • MOP: advanced meta-programming features
    + + = Expressive Language Powerful Libraries Meta Programming
  • Why another Language?
    • Want complete binary compatibility with Java
      • No difference from Java at JVM/bytecode level
      • No wrappers or separate islands of APIs
    • Java code-friendly syntax
      • Don’t want something totally foreign to Java developers
    • Want a scripting language designed:
      • For the Java Platform
      • By Java developers
      • For Java developers
  • Groovy Features
    • Dynamic and (optional) static typing
      • int a = 2
      • def str = &quot;Hello&quot;
    • Native syntax for lists, maps, arrays, beans, etc.
      • def list = [&quot;Rod&quot;, 3, new Date()]
      • def myMap = [Neeta:32, Eric:34]
    • Closures
      • myMap.each( {name, age -> println &quot;$name is $age years old&quot; })
      • >Eric is 34 years old
      • >Neeta is 32 years old
  • Groovy Features (Cont.)
    • Regex built-in
      • if ( &quot;name&quot; ==~ &quot;na.*&quot; ) { println &quot;match!&quot; }
      • -> match!
    • Operator overloading
      • def list = [1, 2, 3] + [4, 5, 6]
      • list.each { print it }
      • -> 123456
    • Autoboxing and polymorphism across collection, array, map, bean, String, iterators, etc.
      • String[] array = ['cat', 'dog', 'mouse']
      • def str = 'hello'
      • Println&quot;${array.size()},${str.size()}, ${list.size()} -> 3,5,6
  • GDK Software
    • Adds convenient methods to JDK
    • String
      • contains(), count(), execute(), padLeft(), center(), padRight(), reverse(), tokenize(), each(), etc.
    • Collection
      • count(), collect(), join(), each(), reverseEach(), find/All(), min(), max(), inject(), sort(), etc.
    • File
      • eachFile(), eachLine(), withPrintWriter(), write(), getText(), etc.
    • Lots there and growing all the time
    • You can add methods programmatically
  • Groovy Markup
    • Native support for hierarchical structures in code
      • XML
      • XHTML
      • Ant
      • Swing
      • SWT
    • Relatively easy to add your own
  • AntBuilder
    • Reuse hundreds of Ant tasks as simple method calls
    • Even create your own build system!
    • def ant = new AntBuilder() def patterns = [&quot;**/*.groovy&quot;, &quot;**/*.java&quot;] ant. sequential { mkdir (dir: &quot;dir1&quot;) copy (todir: &quot;dir1&quot;) { fileset (dir: &quot;dir2&quot;) { for(pattern in patterns) include (name: pattern) } } echo (&quot;done&quot;) }
  • Groovy SQL
    • Easy to use JDBC software thanks to closures
    • def sql = Sql.newInstance(url, usr, pwd, driver) sql.execute(&quot;insert into table values ($foo, $bar)&quot;) sql.execute(&quot;insert into table values(?,?)&quot;, [a, b]) sql.eachRow(&quot;select * from EMPLOYEES&quot;) { print it.name } def list = sql.rows(&quot;select * from EMPLOYEES&quot;)
    • DataSet notion: poor-man ORM
    • def set = sql.dataSet(&quot;EMPLOYEES&quot;) set.add(name: &quot;Johnny&quot;, age: 33) set.each { user -> println user.name } set.findAll { it.age > 22 && it.age < 42 } // LINQ J
  • What is the magic?
    • The dynamic part is coming from the:
      • MOP: Meta Object Protocol
    • At runtime, allows you to
      • Intercept method calls (even non-existing ones)
      • Intercept property accesses
      • Inject new methods or new properties
    • You can create Domain Specific Languages (DSL)
    • With the MOP, come the… builders
      • Builder pattern at the syntax level!
      • MarkupBuilder, SwingBuilder, AntBuilder...
  • Oracle and Groovy
    • Manage your application server with Groovy
    • Groovy Editor for Jdeveloper
    • client = new OC4JClient()
    • client.connect(&quot;localhost&quot;,&quot;23791&quot;,&quot;oc4jadmin&quot;,&quot;welcome1&quot;)
    • defaultApp = client.helper.createGroovyMBean(client.helper.DEFAULTAPP_MBEAN_NAME);
    • println &quot; --> Create ConnectionPool&quot;
    • defaultApp.createJDBCConnectionPool(&quot;MyPool&quot;,
    • &quot;oracle.jdbc.pool.OracleDataSource&quot;,
    • &quot;scott&quot;,
    • &quot;tiger&quot;,
    • &quot;jdbc:oracle:thin:@localhost:1521:xe&quot;)
  • Rapid Web Application Development with
  • Grails: Introduction
    • Grails: MVC web framework inspired by:
        • Convention over Configuration
        • Don’t Repeat Yourself (DRY)
        • Ruby on Rails
    • Built on solid foundations:
        • Spring IoC, MVC and WebFlow
        • Hibernate
        • SiteMesh
  • Demonstration
    • Create an application
  • Project Infrastructure + PROJECT_HOME + grails-app + conf + controllers + domain + i18n + services + taglib + views + lib + spring + hibernate + src + web-app
  • The Application Domain
    • Domain classes hold state and implement behaviour
    • They are linked together via relationships (e.g. one-to-many)
    • In Java domain classes have traditionally been handled by Object-Relational Mapping (ORM)
    • Grails provides simple ORM built on Hibernate
    Source: Please add the source of your data here
  • Grails ORM (GORM)
    • Extremely simple. No special class to extend or file to configure!
    • class ExpenseReport {
    • @Property Long id
    • @Property Long version
    • @Property relatesToMany = [ items :ExpenseItem]
    • @Property Set items
    • @Property Date submissionDate
    • @Property String employeeName
    • }
  • Grails ORM (GORM)
    • We’ve got this far, so lets define the other side!
    • class ExpenseItem {
    • @Property Long id
    • @Property Long version
    • @Property belongsTo = ExpenseReport
    • @Property String type
    • @Property Currency currency
    • @Property Integer amount
    • }
  • Grails Constraints
    • Validation constraints can be defined using the ‘constraints’ property
          • class ExpenseItem {
          • @Property constraints = { type (inList:['travel', 'accomodation'])
          • amount (range:1..999)
          • }
          • }
  • The Controller
    • The controller and action name map to the URI: /expenseReport/list
    • class ExpenseReportController {
    • @Property list = {
    • [expenseReports : ExpenseReport.list()]
    • }
    • }
  • Data Binding & Flow Control
    • // save action
    • @Property save = {
    • def e = ExpenseItem.get(params.id)
    • e.properties = params
    • if(e. save ()){ redirect(action:show,id:e.id)
    • } else {
    • render( view: 'create',
    • model:[expenseItem:e] )
    • }
    • }
  • Groovy Server Pages
    • A view technology very similar to JSP, but with Groovy as the primary language
    • More expressive and concise with support for embedded GStrings & Tags
    • Layout support through integration with SiteMesh
    • Ability to define dynamic tag libraries
    Source: Please add the source of your data here
  • A GSP Example
    • The GSP for the list action is named according to convention: grails-app/views/expenseItem/list.gsp
    • <html>
    • <body>
    • <g:each in=&quot;${expenseItems}&quot;>
    • <p> ${it.type} – amount: ${it.amount} </p>
    • </g:each>
    • </body>
    • </html>
  • Oracle and Grails
    • Grails Application Running on OracleAS
    • Development team is working with Spring and Grails developers to integrate Grails and JPA
    • http://www.oracle.com/technology/tech/java/grails.html
  • A Q & Q U E S T I O N S A N S W E R S
  •